15. 三数之和

本文解析了一道经典的算法题目——三数之和,通过排序和双指针法找到数组中所有不重复的三元组,使三数之和为0,并提供了两种实现方式的Java代码,一种超时,另一种通过AC。

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

知乎ID: 码蹄疾
码蹄疾,毕业于哈尔滨工业大学。
小米广告第三代广告引擎的设计者、开发者;
负责小米应用商店、日历、开屏广告业务线研发;
主导小米广告引擎多个模块重构;
关注推荐、搜索、广告领域相关知识;

题目

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

分析

排序,然后把三个数求和的解就转化为两个数相加等于某个数。
求解两个数相加等于某个数,用双指针法即可。
关键在于处理重复的问题。重复的问题最开始想直接用java的contains方法去做,因为java中contains方法也需要遍历,时间复杂度就不能接受了,第一次提交超时了。
由于拍完序了。所以重复问题的处理只需要判断相邻两个是不是相等,如果相等移动指针即可。

Code

超时的版本

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (nums.length < 3) {
            return res;
        }
        Arrays.sort(nums);

        for (int i = 0; i < nums.length; i++) {
            int l = i + 1;
            int r = nums.length - 1;
            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum == 0) {
                    List<Integer> target = new ArrayList<Integer>();
                    target.add(nums[i]);
                    target.add(nums[l]);
                    target.add(nums[r]);
                    if (!res.contains(target)) {
                        res.add(target);
                    }
                    l++;
                    r--;
                } else if (sum < 0) {
                    l++;
                } else {
                    r--;
                }
            }
        }
        return res;
    }
}

AC版本

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (nums.length < 3) {
            return res;
        }
        Arrays.sort(nums);

        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int l = i + 1;
            int r = nums.length - 1;
            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[l], nums[r]));
                    while (l < r && nums[l] == nums[l + 1]) l++;
                    while (l < r && nums[r] == nums[r - 1]) r--;
                    l++;
                    r--;
                } else if (sum < 0) {
                    l++;
                } else {
                    r--;
                }
            }
        }
        return res;
    }
}

扫码关注
扫码关注更多题解

### C++ 实现三数之和问题 对于寻找数组中个数相加等于零的问题,可以采用双指针方法来优化暴力求解的时间复杂度。具体来说,在遍历过程中固定一个数值作为目标值的相反数,然后利用两个指针对剩余部分进行扫描。 #### 排序与去重 首先对输入数组 `nums` 进行升序排列以便后续操作,并去除重复元素以减少不必要的计算量: ```cpp std::sort(nums.begin(), nums.end()); auto last = std::unique(nums.begin(), nums.end()); nums.erase(last, nums.end()); ``` #### 双指针查找组合 接着定义外层循环用于选取当前考察的目标值;内嵌两层循环分别指向待查区间的两端,逐步向中间靠拢直至找到满足条件的一组解或将要交错为止: ```cpp for (int i = 0; i < nums.size(); ++i) { int target = -nums[i]; int start = i + 1; int end = nums.size() - 1; while (start < end) { if (nums[start] + nums[end] == target) { result.push_back({nums[i], nums[start], nums[end]}); // 跳过相同元素防止重复记录 while (start < end && nums[start] == nums[++start]); while (start < end && nums[end] == nums[--end]); } else if (nums[start] + nums[end] < target) { ++start; } else { --end; } } // 避免再次选到相同的起始点 while (i + 1 < nums.size() && nums[i + 1] == nums[i]) ++i; } ``` 此段代码实现了高效的三数之和查询功能[^1]。为了保证结果集中不含冗余项,在每次成功匹配后均需跳过连续出现的相同数字序列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值