【leetcode15】三数之和 Java题解

leetcode分类下所有的题解均为作者本人经过权衡后挑选出的题解,在易读和可维护性上有优势
每题只有一个答案,避免掉了太繁琐的以及不实用的方案,所以不一定是最优解

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

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

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

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

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums.length < 3) return res;
        Arrays.sort(nums);
        int i = 0;                      //初始指针1
        while(i < nums.length - 2){
            if(nums[i] > 0) break;      
            int j = i + 1;              //指针2从指针1的下一个索引开始
            int k = nums.length - 1;    //指针3从最后一个索引开始
            while(j < k){
                int sum = nums[i] + nums[j] + nums[k];
                if(sum == 0) res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                if(sum <= 0) while(nums[j] == nums[++j] && j < k);
                if(sum >= 0) while(nums[k] == nums[--k] && j < k);  //nums[k--] == nums[k]也对
            }
            while(nums[i] == nums[++i] && i < nums.length - 2);
        }
        return res;
    }
}
  1. 排序
  2. 设置三个指针:两个在前,一个在后
  3. 通过while语句去重和移动指针

你可能感兴趣的:(Leetcode)