Leetcode 15. 3Sum

15. 3Sum

Given an array S of n integers, are there elements a, b, c in S 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.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
 
题目链接:https://leetcode.com/problems/3sum/description/
题目大意:给定数组S,求和为 0 的三个数的组合,要求组合不重复
解题思路:三重循环时间复杂度是O(n^3),先快速排序,时数组递增有序。
                  第一层:第一个数按顺序遍历O(n) ;
                  第二层:第二个数从前往中间遍历,如果总数<0,下标增加,第三个数从最后往中间遍历,如果总数<0,下标增加,O(n) ;                     合起来时间复杂度为O(n^2)
代码:
class Solution {
public:
    vector<vector<int> > threeSum(vector<int>& nums) {
        vector<vector<int> >ans;
        int n = nums.size();
        sort(nums.begin(),nums.end());
        for(int i = 0;i < n - 2;i ++){
            if(nums[i] > 0){
                while(i < n - 3 && nums[i + 1] == nums[i])
                i ++;
                break;
            }
            int j = i + 1,k = n - 1;
            while(j < k){
                if(nums[i] + nums[j] > 0)
                    break;
                while(j < k && nums[i] + nums[j] + nums[k] < 0)
                    j ++;
                while(j < k && nums[i] + nums[j] + nums[k] > 0)
                    k --;
                if(j >= k)
                    break;
                if(nums[i] + nums[j] + nums[k] == 0){
                    vector <int> cur;
                    cur.push_back(nums[i]);
                    cur.push_back(nums[j]);
                    cur.push_back(nums[k]);
                    ans.push_back(cur);                        
                }else{
                    continue;
                }
                while(j + 1 < k && nums[j + 1] == nums[j])
                    j ++;
                while(k - 1 > j && nums[k - 1] == nums[k])
                    k --;
                j ++;
                k --;
            }
            while(i < n - 3 && nums[i + 1] == nums[i])
                i ++;
        }
        return ans;
    }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值