zoukankan      html  css  js  c++  java
  • Leetcode 4Sum

    Given an array S of n integers, are there elements abc, 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)
    与3sum一样
    class Solution {
    public:
        vector<vector<int> > fourSum(vector<int> &num, int target) {
            vector<vector<int> > res;
            int n = num.size();
            if( n < 4) return res;
            sort(num.begin(),num.end());
            for(int i = 0; i < n-3; ++ i){
                if(i !=0 && num[i]== num[i-1]) continue;
                for(int j = i+1; j < n-2; ++ j){
                    if(j!=i+1 && num[j] == num[j-1] ) continue;
                    int start = j+1, end = n-1;
                    while(start < end){
                        int sum = num[i]+num[j]+num[start]+num[end];
                        if(sum > target) end--;
                        else if(sum < target) start++;
                        else{
                            vector<int> a;
                            a.push_back(num[i]);a.push_back(num[j]);
                            a.push_back(num[start]);a.push_back(num[end]);
                            res.push_back(a);
                            do{start++;}while(start < end && num[start] == num[start-1]);
                            do{end--;}while(start < end && num[end] == num[end+1]);
                        }
                    }
                }
            }
            return res;
        }
    };
    
    
    
     
  • 相关阅读:
    zepto.js常用操作
    使用require.js
    iscroll.js文档
    EasyUI Resizable 可调整尺寸
    EasyUI Droppable 可放置
    EasyUI Draggable 可拖动
    EasyUI Parser 解析器
    EasyUI Easyloader 加载器
    Jquery EasyUI插件
    从MySQL随机选取数据
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3824058.html
Copyright © 2011-2022 走看看