15. 三数之和

2019-08-07  本文已影响0人  爱情小傻蛋

一、题目

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

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

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

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

二、解答

2.1方法一:双指针法
2.1.1 思路
2.1.2 代码实现
public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        //数组大小小于3
        if (nums == null || nums.length < 3){
            return res;
        }
        //排序
        Arrays.sort(nums);

        int len = nums.length;

        for (int i = 0 ; i < len; i++){
            if (nums[i] > 0)
                break;

            //去重
            if (i > 0 && nums[i] == nums[i-1]){
                continue;
            }

            int l = i + 1;
            int r = len - 1;
            while (l < r && r > 0){
                int sum = nums[i] + nums[l] + nums[r];

                if(sum == 0){
                    List<Integer> temp = new ArrayList<Integer>();
                    temp.add(nums[i]);
                    temp.add(nums[l]);
                    temp.add(nums[r]);
                    res.add(temp);

                    //去重
                    while (l < len-1 && nums[l] == nums[l+1]) l++;
                    while (r > 0 && nums[r] == nums[r-1]) r--;

                    r--;
                    l++;
                }else if (sum < 0){
                    l++;
                }else {
                    r--;
                }
            }
        }
        return res;
    }
上一篇 下一篇

猜你喜欢

热点阅读