版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012668018/article/details/62418080
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].
Subscribe to see which companies asked this question.
第一种最直观的方法就是两次遍历:
public static int[] twoSum(int[] numbers, int target) {
for(int i = 0; i < numbers.length; i++) {
for(int j = i + 1; j < numbers.length; j++) {
if(numbers[i] + numbers[j] == target)
return new int[]{i, j};
}
}
return null;
}
看了下其他的答案,有个比较巧妙的,一次遍历就可以做到,也就是时间复杂度是O(n),线性增长。大致原理是借用了Java的Map,如下:
public static 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;
}
本质上就是在第一次遍历的同时,把相关信息保存到其他地方,这里就是放到一个map里面。在原数组中key是数组下标,value是元素值;放到map中恰好反了过来,key成了元素值,而value是数组下标。
遍历过的元素都被当成key存到map里,而对应的value就是它的下标。所以从第二个元素开始,只需要看看它和map中某个key的和是否为target就行,不行就把它存到map中,继续遍历。
讲道理,这个方法,巧是巧,就是有点钻空子了。首先一点,我个人觉得在这种算法题中,最好不要使用Java的API,因为这是别人的东西, 体现不出你的能力;第二,使用了map本质上是以空间换时间,因为只使用一次遍历的话,必然要采取一些手段保存遍历过的信息。就算使用了map,表面上简化了代码(好像也没有),提升了效率,但是在map中搜索key不花费时间吗?这个时间复杂度要怎么算?
但是第一种方法确实费时间,目前也没有比第二种更省时的。