题目描述:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
2种做法,第一种先排序,然后用双指针,一个在前,一个在后,一起往中间靠拢,时间复杂度O(n*logn)(注意:这里排序的话就把位置打乱了,所以要用Pair来记住位置);第二种牺牲空间换时间,采用hashmap,时间复杂度O(n)。
第一种做法:
class Pair implements Comparable<Pair>{
private int val;
private int index;
public int getVal() {
return val;
}
public int getIndex() {
return index;
}
public Pair(int val, int index) {
super();
this.val = val;
this.index = index;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.val>o.val)
return 1;
else if(this.val<o.val)
return -1;
return 0;
}
}
public int[] twoSum(int[] nums, int target) {
Pair[] pairs=new Pair[nums.length];
for (int i = 0; i < nums.length; i++) {
pairs[i]=new Pair(nums[i], i+1);
}
int[] a=new int[2];
int i=0,j=pairs.length-1;
Arrays.sort(pairs);
while(i<j){
if(pairs[i].getVal()+pairs[j].getVal()==target){
a[0]=pairs[i].getIndex();a[1]=pairs[j].getIndex();return a;
}else if(pairs[i].getVal()+pairs[j].getVal()<target){
i++;
}else{
j--;
}
}
return null;
}
第二种做法:
public int[] twoSum(int[] nums, int target) {
int[] a=new int[2];
HashMap<Integer, Integer> map=new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
Integer val=map.get(nums[i]);
if(val==null)
map.put(nums[i], i);
Integer n=map.get(target-nums[i]);
if(n!=null&&n<i){
a[0]=i;
a[1]=n;
return a;
}
}
return null;
}
这里的n!=null&&n