zoukankan      html  css  js  c++  java
  • [LeetCode] 4Sum

    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, abcd)
    • 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)
    
    分析:在3Sum基础上稍做改动写的程序
    class Solution {
    public:
        vector<vector<int> > fourSum(vector<int> &num, int target) {
            vector<vector<int> > result;
            int len = num.size();
            if(len<4)
                return result;
            int sum;
            sort(num.begin(),num.end());
            for(int mid2 = 2;mid2<len-1;mid2++){
            
                for(int mid = 1;mid<mid2;mid++){
                   int low = 0,up = len-1;
                   while(low<mid && mid2<up){
                       if(low < mid-1 && low>0 && num[low] == num[low-1]){
                           low++;
                           continue;
                       }
                       if(up > mid2+1 && up<len-1 && num[up] == num[up+1]){
                           up--;
                           continue;
                       }
                       sum  = num[low] + num[mid] + num[mid2] + num[up];
                       if(sum == target){
                           vector<int> temp;
                           temp.push_back(num[low]);
                           temp.push_back(num[mid]);
                           temp.push_back(num[mid2]);
                           temp.push_back(num[up]);
                           if(find(result.begin(),result.end(),temp)== result.end())
                               result.push_back(temp);
                       
                       }else if(sum>target){
                          up--;
                          continue;
                       }else
                       {
                          low++;
                          continue;
                       }
                    low++;
                    up--;
    
                   }//end while
                }//end for
            }//end for
            return result;
        }
    };
  • 相关阅读:
    ORACLE查询删除重复记录三种方法
    是否可以从一个static方法内部发出对非static方法的调用
    协程(微线程)
    多线程、多进程
    python3.6.5修改print的颜色
    Python之时间和日期模块
    Python之字符(2)
    Python之字符
    python之列表
    Python中的文件操作
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3905772.html
Copyright © 2011-2022 走看看