【leetcode】15. 3sum

本文详细介绍了解决3SUM问题的算法实现过程,通过排序和哈希表优化,达到O(n^2)的时间复杂度。包括代码实现、时间复杂度分析及运行效率评估。

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

基本思路:排序,然后从第一个元素开始遍历,期间用到夹逼原理。

同时由于要排除duplicate的答案,所以需要对每个连续相同的元素中,只处理一次。

参考网址:https://en.wikipedia.org/wiki/3SUM

</pre><pre name="code" class="cpp">/** 
 * @author          johnsondu 
 * @problem         3sum
 * @url             https://leetcode.com/problems/3sum/
 * @timeComlexity   O(n^2) 
 * @spaceComplexity O(1) 
 * @strategy        Inserting each number nums[i] into a hash table, 
 *                    and then for each index i and j, checking whether
 *                    the hash table contains the integer -(s[i] + s[j])
 * @status          Accepted, runtime beats 61.08% of cpp submissions 
 * @time            17:10, Oct 21 2015 
 */  
 
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        if(nums.size() < 3) return ans;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < nums.size() - 2; i ++) {
            // in case of duplicate solutions
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int a = nums[i];
            int lf = i + 1;
            int rt = nums.size() - 1;
            while(lf < rt) {
                int b = nums[lf];
                int c = nums[rt];
                if(0 == a + b + c) {
                    ans.push_back(vector<int> {a, b, c});
                    // in case of duplicate solutions
                    while(lf < nums.size() && nums[lf] == b) lf ++;
                    // in case of duplicate solutions
                    while(rt >= 0 && nums[rt] == c) rt --;
                }
                else if(a + b + c > 0) rt --;
                else lf ++;
            }
        }
        return ans;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值