Question
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
我的最初解法:时间复杂度O(nlogn)
两个for循环,外层循环从i=0到数组length-1,内层循环是从i+1到length,检验每个循环的nums[i] + nums[j] == target,
public class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0;i < nums.length - 1; i++) {
for(int j = i+1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i,j};
}
}
}
return null;
}
}
最佳解法:时间复杂度O(n)
只用单词遍历nums[]。使用HashMap,将nums[i]作为键,索引i为值,每次遍历前线检查Map中是否有target-i,若有则匹配成功,寻找完毕,如无则将当前的nums[i]和i作为键值对存入。
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[1] = i;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i );
}
return result;
}