题目:
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].
给定一个整数数组和一个特定的值,返回相加等于特定值的两个数的索引,假设对每一个输入只有一个答案,相同的元素不可使用两次。
思路:
1.利用hashmap,遍历nums数组,如果nums[i]和hashmap中的某个数相加等于target,得到答案返回,否则,将nums[i]和i作为key和value存入hashmap。
hashmap的containsKey(key)方法,判断集合中是否包含指定的key;get(key)方法判断集合中是否包含指定的key,
put(K key, V value) (可以相同的key值,但是添加的value值会覆盖前面的,返回值是前一个,如果没有就返回null)
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int [] res=new int[2];
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
res[0]=map.get(target-nums[i]);
res[1]=i;
break;
}
else
map.put(nums[i],i);
}
return res;
}
}
算法时间复杂度为O(n),containskey时间复杂度为O(1)
2.看到array和target,想到二分法,但是这道题不是舍弃一半在另一半查找,而是先将array排序,设立low和high指针,当low和high的值相加等于target,得到结果返回,当low和high的值相加大于target,high--,当low和high的值相加小于target,low++。注意;需要把得到的两个值在原数组中找到index,因为已经排序了,原先的index已经被打乱。
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] temp=new int[nums.length];
System.arraycopy(nums,0,temp,0,nums.length);
Arrays.sort(temp);
int [] res=new int[2];
int [] trueres=new int[2];
int low=0;
int high=temp.length-1;
while(low<high){
if(temp[low]+temp[high]==target){
res[0]=low;
res[1]=high;
break;
}
else if(temp[low]+temp[high]<target)
low++;
else
high--;
}
int temp1=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==temp[low]&&temp1==0){
trueres[0]=i;
temp1=1;
}
else if(nums[i]==temp[high])
trueres[1]=i;
}
Arrays.sort(trueres);
return trueres;
}
}
注意,如果数组中有重复数字,最后找原index的时候,注意不要找重,可以设置一个temp1.
数组复制方法:System,arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
类似题目: