三数之和---左右指针中间移动

1,leetcode原文

https://leetcode-cn.com/problems/3sum/

2,题目

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

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

 

示例:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

3,源码如下

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

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

        Arrays.sort(nums);//先排序

        for(int k = 0;k<nums.length-1;k++){
            if(nums[k]> 0){//如果k对应的值已经大于0,肯定不满足条件,无需后续判断
                break;
            }

            if(k>0 && nums[k]== nums[k-1]){//如果和前一个值一样,也无需执行
                continue;
            }

            for(int i = k+1,j=nums.length-1;i<j;){//开始处理两个边界指针
                int temp = nums[k]+nums[i]+nums[j];
                if(temp > 0 ){
                    --j;
                }else if(temp < 0){
                    ++i;
                }else{
                    results.add(Arrays.asList(nums[k],nums[i],nums[j]));
                    while (i<j && nums[i] == nums[++i]);
                    while (i<j && nums[j] == nums[--j]);
                }
            }
        }

        return results;

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章