问题定义
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].
给定一个数组和一个数据,找到数组中两个数的和等于给定的数据的位置。
我的思路
从数组中第一个数开始进行逐个遍历,每次遍历的数都和它后面的数值进行加和运算,判断加和是否与给定的数据相等,若相等,返回两个被加数的位置并退出循环。
思路是比较简单粗暴啦。时间复杂度为O(n^2)。
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int n;
n=nums.length;
int[] a=new int[2];
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(nums[i]+nums[j]==target)
{a[0]=i;a[1]=j;}
}
}
return a;
}
}
学习其他人的代码
来自一位叫jiaming2的码友。
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 + 1;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i + 1);
}
return result;
}
主要使用了字典,可以根据数值直接找出其位置。他的这种思路,时间复杂度就降到了O(n),只需知道一个加数就能直接找出第二个加数的位置,很巧妙,比我的简单粗暴聪明多了。
里面用了java集合类Map,通过key值来找value。这其实也是我比较喜欢java的一个原因,有强大的类库,方便我去解决问题。