The first question of leetcode, this method can achieve O(n) complexity solution
The question requires an int[], such as nums = [2, 7, 11, 15], and a target = 9.
If there are two numbers whose sum is the target value, for example nums[0] nums[1] = 2 7 = 9
return [0, 1].
When using the following solution, I have a little doubt, that is, a new hashmap is created, but no value is assigned to it. In this case, how do you achieve the question requirements?
public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Map map = new HashMap(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { result[1] = i + 1; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i + 1); } return result; }
Isn’t map.put() in the for loop an assignment? ? ?
The question requires that the sum of two numbers be the target value and a given value, then you must traverse at least two numbers. The realization of this situation is:
(1) If you initialize first, it will take algorithm time O(n); then traverse to find the first When the value is correct, the algorithm time is O(k), 0
1) Initialize the map first,
2) Traverse the first number 2, target - 2 = 9 - 2 = 7
3) Judge that 7 is also in the map and return the correct result.
Note: Traverse to the first correct number
(2) If it is not initialized, it will traverse to the second correct number before stopping. The algorithm time is O(k)(1
No
Key
的情况下,HashMap.containsKey(Key)
返回的是false
不包括Key
.There will be no null pointer error as you think.