LeetCode-3Sum

本文介绍了一种解决特定编程问题的方法:在给定数组中寻找三个整数,使得这三个整数的和为零。文章详细阐述了解决方案的设计思路,并通过具体的代码示例解释了如何使用双指针技巧来高效地解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Note:
The solution set must not contain duplicate triplets.

Example:
Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

题意:给定一个整型数组,在数组中找出三个数,使其和为0;

解法:对于x+y+z=0来说,要找到三个数之和为0,即找到两个数之和满足x+y=-z;因此,对于第一个数来说,如果已经大于0了,那么肯定不存在另外两个数使其满足条件了;除了特殊情况的[0,0,0]来说,第一个数为负数,后面要找的两个数之和为第一个数的负数,另其为target,那么第二个数x我们可以从其后一个位置开始往后找,而第三个数y从数组的末尾开始找,这个时候会有三种情况:

  1. if x+y == target,满足条件
  2. if x+y > target,说明相加的数字过大,那么末尾的那个数可以向前遍历
  3. if x+y < target,说明相加的数字过小,那么第二个数可以向后遍历

要注意的是需要考虑得到重复的结果,因此我们需要跳过相同数字的情况;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new LinkedList<List<Integer>>();
        Arrays.sort(nums);
        for(int i=0; i<nums.length; i++){
            if(nums[i] > 0) break;
            if(i > 0 && nums[i] == nums[i-1]) continue;//跳过重复的数字
            int st = i + 1;
            int ed = nums.length - 1;
            int target = 0 - nums[i];//剩余的两数之和
            while(st < ed){
                if(nums[st] + nums[ed] == target){
                    List<Integer> x = new LinkedList<>();
                    x.add(nums[i]);
                    x.add(nums[st]);
                    x.add(nums[ed]);
                    result.add(x);
                    //跳过重复的数字
                    while(st < ed && nums[st] == nums[st + 1]) st++;
                    while(st < ed && nums[ed] == nums[ed - 1]) ed--;
                    st++;
                    ed--;
                }
                else if(nums[st] + nums[ed] > target) ed--;
                else st++;
            }
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值