LeetCode-TwoSum问题

我的解法:借用HashMap,时间复杂度O(n),空间复杂度O(n)

public  int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int i = 0;
for(Integer num : nums){
map.put(num,i++);
}
int m = 0;
int n = 0;
for(Integer num : nums){
int other = target-num;
if(map.containsKey(other) && m!=map.get(other)){
n = map.get(target-num);
break;
}
m++;
}
if(n==0){
return new int[]{};
}
return new int[]{m,n};
}



网友的解法:
1)先对原数组排序,使其成为递增数据
2)对排序后的数组头部arr[i] 和尾部arr[j]相加,如果等于target,打印下标 然后执行4);否则执行3)
3)如果小于target,i++;如果大于target,j--
4)i++,j--继续执行2)
5)当i==j时,退出





posted @ 2017-04-24 21:49  扬大宝  阅读(212)  评论(0编辑  收藏  举报