[LeetCode]18.4Sum

【题目】

4Sum

 Total Accepted: 3493 Total
Submissions: 16137My Submissions

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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.
    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)

【题意】

给定n个整数的数组S,是否在 数组S中有元素a,b,c,d,使得a + b + c + d = target?在数组中找出独一无二的四元素组,使得他们之和为target。

注意:

在四元素组(a,b,c,d)中,必须满足非递减排序。 (即a≤b≤c≤d)

该解决方案集中一定不能包含重复的四元素组。

【分析】

  1. 对数组排序
  2. 确定四元数中的前两个(a,b)
  3. 遍历剩余数组确定两外两个(c,d),确定cd时思路跟3Sum确定后两个数据一样,二分查找左右逼近。
  4. 在去重时采用set集合

【代码】

/*********************************
*   日期:2014-01-18
*   作者:SJF0115
*   题号: 4Sum
*   来源:http://oj.leetcode.com/problems/4sum/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        int i,j,start,end;
        int Len = num.size();
        vector<int> triplet;
        vector<vector<int>> triplets;
        set<vector<int>> sets;
        //排序
        sort(num.begin(),num.end());
        for(i = 0;i < Len-3;i++){
            for(j = i + 1;j < Len - 2;j++){
                //二分查找
                start = j + 1;
                end = Len - 1;
                while(start < end){
                    int curSum = num[i] + num[j] + num[start] + num[end];
                    //相等 -> 目标
                    if(target == curSum){
                        triplet.clear();
                        triplet.push_back(num[i]);
                        triplet.push_back(num[j]);
                        triplet.push_back(num[start]);
                        triplet.push_back(num[end]);
                        sets.insert(triplet);
                        start ++;
                        end --;
                    }
                    //大于 -> 当前值小需要增大
                    else if(target > curSum){
                        start ++;
                    }
                    //小于 -> 当前值大需要减小
                    else{
                        end --;
                    }
                }//while
            }
        }//for
        //利用set去重
        set<vector<int>>::iterator it = sets.begin();
        for(; it != sets.end(); it++)
            triplets.push_back(*it);
        return triplets;
    }
};
int main() {
    vector<vector<int>> result;
    Solution solution;
    vector<int> vec;
    vec.push_back(-3);
    vec.push_back(-2);
    vec.push_back(-1);
    vec.push_back(0);
    vec.push_back(0);
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    result = solution.fourSum(vec,0);
    for(int i = 0;i < result.size();i++){
        for(int j = 0;j < result[i].size();j++){
            printf("%d ",result[i][j]);
        }
        printf("\n");
    }
    return 0;
}

【测试】

Input: [-1,0,1,2,-1,-4], -1
   
Expected: [[-4,0,1,2],[-1,-1,0,1]]
Input: [-3,-2,-1,0,0,1,2,3], 0
   
Expected: [[-3,-2,2,3],[-3,-1,1,3],[-3,0,0,3],[-3,0,1,2],[-2,-1,0,3],[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
时间: 2024-09-09 14:58:59

[LeetCode]18.4Sum的相关文章

LeetCode 18 4Sum(4个数的和)

翻译 给定一个有n个数字的数组S,在S中是否存在元素a,b,c和d的和恰好满足a + b + c + d = target. 找出数组中所有的不想等的这四个元素,其和等于target. 备注: 在(a,b,c,d)中的元素必须从小到大排列.(a ≤ b ≤ c ≤ d) 其结果必须不能够重复. 例如,给定S = {1 0 -1 0 -2 2},target = 0. 一个结果集为: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2) 原文 Given an ar

LeetCode 16 3Sum Closest(最接近的3个数的和)

翻译 给定一个有n个整数的数组S,找出S中3个数,使其和等于一个给定的数,target. 返回这3个数的和,你可以假定每个输入都有且只有一个结果. 例如,给定S = {-1 2 1 -4},和target = 1. 那么最接近target的和是2.(-1 + 2 + 1 = 2). 原文 Given an array S of n integers, find three integers in S such that the sum is closest to a given number,

LeetCode 15 3Sum(3个数的和)

翻译 给定一个有n个整数的数组S,是否存在三个元素a,b,c使得a+b+c=0? 找出该数组中所有不重复的3个数,它们的和为0. 备注: 这三个元素必须是从小到大进行排序. 结果中不能有重复的3个数. 例如,给定数组S={-1 0 1 2 -1 4},一个结果集为: (-1, 0, 1) (-1, -1, 2) 原文 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? F

&lt;font color=&quot;red&quot;&gt;[置顶]&lt;/font&gt;

Profile Introduction to Blog 您能看到这篇博客导读是我的荣幸,本博客会持续更新,感谢您的支持,欢迎您的关注与留言.博客有多个专栏,分别是关于 Windows App开发 . UWP(通用Windows平台)开发 . SICP习题解 和 Scheme语言学习 . 算法解析 与 LeetCode等题解 . Android应用开发 ,而最近会添加的文章将主要是算法和Android,不过其它内容也会继续完善. About the Author 独立 Windows App 和

leetcode难度及面试频率

转载自:LeetCode Question Difficulty Distribution               1 Two Sum 2 5 array sort         set Two Pointers 2 Add Two Numbers 3 4 linked list Two Pointers           Math 3 Longest Substring Without Repeating Characters 3 2 string Two Pointers      

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能

4Sum:LeetCode

这道题要求跟3Sum差不多,只是需求扩展到四个的数字的和了.我们还是可以按照3Sum中的解法,只是在外面套一层循环,相当于求n次3Sum.我们知道3Sum的时间复杂度是O(n^2),所以如果这样解的总时间复杂度是O(n^3).代码如下: public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { ArrayList<ArrayList<Integer>> res = new Ar

LeetCode之K sum problem

做过leetcode的人都知道, 里面有2sum, 3sum(closest), 4sum等问题, 这些也是面试里面经典的问题, 考察是否能够合理利用排序这个性质, 一步一步得到高效的算法. 经过总结, 本人觉得这些问题都可以使用一个通用的K sum求和问题加以概括消化, 这里我们先直接给出K Sum的问题描述和算法(递归解法), 然后将这个一般性的方法套用到具体的K, 比如leetcode中的2Sum, 3Sum, 4Sum问题. 同时我们也给出另一种哈希算法的讨论. leetcode求和问题

刷leetcode是什么样的体验?【转】

转自:https://www.zhihu.com/question/32322023   刷leetcode是什么样的体验? https://leetcode.com/ 1 条评论   默认排序 按时间排序 75 个回答   糊你熊脸 鹰的眼睛!熊的力量!鱼的记忆! 71 人赞同 找工作那段闹心的日子里看书看累了?刷几题吧-心慌气短压力大?刷几题吧-不知道要做啥?还是刷几题吧-居家旅行,缓解压力,清空罪槽必备良药- 刷Leetcode的主要作用,在我看来,其实是为了维持一种编程状态. 小生在某小