LeetCode--015--三元之和(java)

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

i做主线的遍历,从头至尾寻找满足条件的其他两个数字。
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0;i < nums.length-2;i++){
            if(i > 0 && nums[i] == nums[i - 1])continue;//一定要加这一句,否则会重复,所给例子会输出两个[-1,1,0]
            int low = i + 1,high = nums.length-1,sum = 0 - nums[i];
            while(low < high){
                if(nums[low] + nums[high] == sum){
                res.add(Arrays.asList(nums[i],nums[low],nums[high]));
                while(low < high && nums[low] == nums[low + 1]) low++;
                while(low < high && nums[high] == nums[high - 1]) high--;
                low ++;
                high--;
                }else if(nums[low] + nums[high] < sum){
                    low ++;
                }else high--;
            }
            
        }
        return res;
    }
}

 2019-04-14 09:49:33

posted @ 2019-04-14 09:49  Assange  阅读(210)  评论(0编辑  收藏  举报