看到这种题第一反应是暴力穷举,尝试了下,可以解决,代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
int a[]={0,0};
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
a[0]=i;
a[1]=j;
}
}
}
return a;
}
}
但是速度76 ms。
看了大神们hashmap的思想,更改了代码,只需要2ms
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0, len = nums.length; i < len; ++i) {
if (map.containsKey(target - nums[i])) { //containsKey是判断该key在map中是否有key存在
return new int[]{map.get(target - nums[i]), i};//get方法获取指定键名的键值对象
} else {
map.put(nums[i], i);
}
}
return res;
}