three sum

2017-06-02  本文已影响0人  yanyuchen

这题就是sort之后用2 points (while)注意要去重来着。

public class Solution {    

public List> threeSum(int[] A) {    int target = 0;List>res = new ArrayList>();if (A == null || A.length < 2)return res;Arrays.sort(A);    for(int i = 0; i< A.length - 2; i++){    if(i > 0 && A[i] == A[i-1]) {        continue;    }        int start = i + 1;    int end = A.length - 1;    while(start < end){        int sum = A[start] + A[end] + A[i];        if(sum < target){            start++;            continue;        }        if(sum > target){            end--;            continue;        }        if(sum == target){            Listtemp = new ArrayList<>();

temp.add(A[start]);

temp.add(A[end]);

temp.add(A[i]);

res.add(temp);

while(start + 1 < end &&A[start] == A[start+1]) start++; //duplicate

while(end-1 > start &&A[end] == A[end -1])  end--;

start++;

end--;

continue;

}

start++;

end--;

}

}

return res;

}

}

上一篇下一篇

猜你喜欢

热点阅读