在遇到一類題目時,通過雙for循環也可暴力破解,但我們可以通過用hashmap來代替一次for循環節約時間開支,在算法上屬于用空間換時間,也能幫助我們更好的理解hashmap這一種重要數據結構,并熟悉hashmap的重要方法。
1.兩數之和
class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();for (int i = 0; i < nums.length; ++i) {if (hashtable.containsKey(target - nums[i])) {return new int[]{hashtable.get(target - nums[i]), i};}hashtable.put(nums[i], i);}return new int[0];}
}
兩數之和hashtable.containsKey更像一次隱藏的for循環
219. 存在重復元素?Ⅱ219. 存在重復元素?
class Solution {public boolean containsNearbyDuplicate(int[] nums, int k) {Map<Integer, Integer> map = new HashMap<Integer, Integer>();for (int i = 0; i < nums.length; ++i){if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k){return true;}map.put(nums[i], i);}return false;}
}
1512. 好數對的數目
?
class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();for (int i = 0; i < nums.length; ++i) {if (hashtable.containsKey(target - nums[i])) {return new int[]{hashtable.get(target - nums[i]), i};}hashtable.put(nums[i], i);}return new int[0];}
}
?