您的位置:首页 > 其它

leetcode-15

2016-05-24 21:56 302 查看
题目:

Given an array S of n integers, are there elements a, b, c in S such that a + b + c =
0? Find all unique triplets in the array which gives the sum of zero.

Note:

Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)


Subscribe to see which companies asked this question

代码:
public class Solution {

      public List<List<Integer>> threeSum(int[] nums){

    int left, right;

    int len = nums.length;

    List<List<Integer>> res = new ArrayList<List<Integer>> ();

    if(nums == null || nums.length < 3)

    return res;

    Arrays.sort(nums);

   

    for(int i = 0; i < len - 2; i++){

     

    if(i != 0 && nums[i] == nums[i - 1] )

    continue;

   

    left = i + 1;

    right = len - 1;

    while(left < right)

    {

    if(nums[i] + nums[left] + nums[right] == 0)

    {

    List<Integer> list = new ArrayList<>();

    list.add(nums[i]);

    list.add(nums[left]);

    list.add(nums[right]);

    res.add(list);

    left++;

    right--;

    while(left < right && nums[left] == nums[left-1])

    left++;

    while(left < right && nums[right] == nums[right+1])

    right--;

    }

    else if(nums[i] + nums[left] + nums[right] < 0)

    left++;

    else

    right--;

    }

    }

    return res;

   

    }

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