您的位置:首页 > 其它

leetcode:two sum的三种解法

2015-04-15 20:16 507 查看
Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

最容易想到的解法就是循环遍历,时间复杂度为O(n2)

public static int[] twoSum(int[] numbers, int target) {
int[] ret = new int[2];
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
ret[0] = i + 1;
ret[1] = j + 1;
}
}
}
return ret;
}


改进一点,先使用快速排序,时间复杂度为O(nlogn),再分别在数组头尾设置两个标记,每次比较头尾两个数的和,如果比target小,头标记右移,如果大,尾标记左移。需要注意记录快速排序前后数字的位置变化。

class Pair implements Comparable<Pair>{
public int number;
public int idx;
public Pair(int number, int idx){
this.number = number;
this.idx = idx;
}
public int compareTo(Pair other){
return this.number - other.number;
}
}
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int n = numbers.length;
Pair[] pairs = new Pair
;
for(int i = 0; i < n; ++i){
pairs[i] = new Pair(numbers[i], i + 1);
}
Arrays.sort(pairs);
int [] result = new int[2];
int begin = 0;
int end = n - 1;
while(begin < end){
if(pairs[begin].number + pairs[end].number < target){
begin++;
}
else if (pairs[begin].number + pairs[end].number > target){
end--;
}
else{
if(pairs[begin].idx > pairs[end].idx){
result[0] = pairs[end].idx;
result[1] = pairs[begin].idx;
}else{
result[0] = pairs[begin].idx;
result[1] = pairs[end].idx;
}
break;
}
}
return result;
}
}


还可以再改进点,使用hashmap,将时间复杂度降低到O(N);

public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];

for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
int index = map.get(numbers[i]);
result[0] = index+1 ;
result[1] = i+1;
break;
} else {
map.put(target - numbers[i], i);
}
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode twosum