Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
“Two Sum” 是LeetCode 开篇之题,相当于我们每次背GRE单词Abandon一样经典。不过说实话这题我来回看了好多次,每次想刷题最后都自己各种找理由最后没坚持下去。所以这次决定边刷题边做总结督促自己学习。
这题首先想到的就是暴力解法,运用俩次loop循环找到解,这样做的时间复杂度自然就比较高O(n^2), 所以又考虑有没有别的方案可以减少loop次数。最后发现可以构造一个HashMap,利用containKey()来减少二次循环查找,而且HashMap是常数级的查找效率。
最后代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int complete = target - nums[i];
if(map.containsKey(complete)){
return new int[]{map.get(complete), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}