题目
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].
哈希表
一般如果数组有序的话,可以使用前后指针方法得到两数和与target比较。
class Solution {
public int[] twoSum(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while(left<right){
int ssum = nums[left]+nums[right];
if(ssum==target)
return new int[]{left,right};
else if(ssum<target)
left ++;
else if(ssum>target)
right --;
}
return new int[]{-1,-1};
这题没有说明是有序数组,所以可以是无序的,如果想用前后指针的方法的话可以先进行排序。也可以使用哈希表的方式将元素映射到索引,然后查找当前元素的余数是否在哈希表中。
class Solution {
public int[] twoSum(int[] nums, int target) {
int n=nums.length;
Map<Integer,Integer> index = new HashMap<>();
for(int i=0;i<n;i++)
index.put(nums[i],i);
for(int i=0;i<n;i++){
int other = target-nums[i];
if(index.containsKey(other) && index.get(other)!=i){
return new int[]{i,index.get(other)};
}
}
return new int[]{-1,-1};
}
}