开始LettCode的刷题之旅,坚持!
平生不识TwoSum,刷尽LeetCode也枉然
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].
Java代码实现:
public static int[] TwoSum(int[] arr,int target){
HashMap<Integer, Integer> hashMap=new HashMap<Integer, Integer>();
int[] result=new int[2];
for(int i=0;i<arr.length;++i){
hashMap.put(arr[i],i);
}
for(int i=0;i<arr.length;++i){
int n=target-arr[i];
if(hashMap.containsKey(n)&&hashMap.get(n)!=i){
result[0]=i;
result[1]=hashMap.get(n);
break;
}
}
return result;
}
public int[] TwoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
if (m.containsKey(target - nums[i])) {
res[0] = i;
res[1] = m.get(target - nums[i]);
break;
}
m.put(nums[i], i);
}
return res;
}