前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 18 4Sum

Leetcode 18 4Sum

作者头像
triplebee
发布2018-01-12 15:10:40
5380
发布2018-01-12 15:10:40
举报

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

代码语言:javascript
复制
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

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

想了半天还以为有什么高深的算法,没想到题解和之前的两道3Sum一样,两点法,没什么好说的。

有很多人想了很多判断条件去优化程序效率,我觉得没什么必要,于是直接在15的代码上改了。

附上前两道3Sum的地址,会做以后这题就肯定没问题了!

https://cloud.tencent.com/developer/article/1019316

https://cloud.tencent.com/developer/article/1019317

代码语言:javascript
复制
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        vector<vector<int>> result;
        int len=(nums.size()-3);
        for(int i=0;i<len;i++)
        {
            if(i!=0 && nums[i]==nums[i-1])continue;
            for(int j=i+1;j<(len+1);j++)
            {
                if(j!=i+1 && nums[j]==nums[j-1])continue;
                int l=j+1,r=nums.size()-1;
                while(l<r)
                {
                    int com=nums[i]+nums[j]+nums[l]+nums[r];
                    if(com>target)
                        r--;
                    else if(com<target)
                        l++;
                    else
                    {
                        result.push_back({nums[i], nums[j], nums[l], nums[r]});
                        while(l<r && nums[l]==nums[l+1]) l++;
                        while(l<r && nums[r]==nums[r-1]) r--;
                        r--;
                        l++;
                    }
                }
            }
        }
        return result;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-08-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档