zoukankan      html  css  js  c++  java
  • leetCode3

    //give a target,find the closet three number,
    //and compute the sum of the closet number
    int threeClosetSum(int A[],int len,int target)
    {
        if (len < 3) return -1;
        std::vector<int> v(A,A+len);
    
        auto last = v.end();
        std::sort(v.begin(), v.end());
    
        int gap = 0;
        int min_gap = __INT_MAX__;
        int result;
        for(auto a = v.begin(); a < std::prev(last,2); a++)
        {
            auto b = std::next(a);
            auto c = std::prev(last);
            while(b < c)
            {
                int sum = *a + *b + *c;
                gap = abs(sum - target);
    
                if(gap < min_gap)
                {
                    min_gap = gap;
                    result = sum;
                }
    
                if(sum > target) c--;
                else if(sum < target) b++;
                else return target;
            }    
        }
        return result;
    }
    
    
    
    using std::vector;
    std::vector<std::vector<int>> fourSum(int A[],int len,int target)
    {
        vector<vector<int>> result;
        if(len < 4)  return result;
    
        vector<int> v(A,A+len);
        std::sort(v.begin(), v.end());
        std::unordered_map<int, vector<std::pair<int,int>>> cache;
    
        for(auto a =0;a<v.size();a++)
        {
            for(auto b=a+1;b<v.size();b++)
            {
                cache[v[a]+v[b]].push_back(std::pair<int, int>(a,b));
            }
        }
    
        for(auto c = 0;c<v.size();c++)
        {
            for(auto d = c+1;d<v.size();d++)
            {
                int key = target - v[c] - v[d];
                if(cache.find(key) == cache.end())  continue;
    
                auto& it = cache[key];  
                for(auto i = 0;i<it.size(); i++)
                {
                    if (c <= it[i].second)
                            continue;          // 有重叠
                    result.push_back({v[it[i].first],v[it[i].second],v[c],v[d]});
                }
            }
        }    
        sort(result.begin(), result.end());
        result.erase(std::unique(result.begin(),result.end()),result.end());
        return result;
    }
    
    
    
    int main()
    {
        int A[]  = {1,0,-1,0,-2,2};
        vector<vector<int>> result = fourSum(A, 6, 0);
        for(auto i =0;i<result.size();i++)
        {
            for(auto j : result[i])
            {
                std::cout << j << "  ";
            }
            std::cout << std::endl;
        }
      
        return 0;
    }

     参考:http://pan.baidu.com/s/1i3vVPgp

  • 相关阅读:
    CentOS6.5安装Tab增强版:bash-completion
    005_linux下logrotate 配置和理解
    ITIL与ITSM的联系与区别
    C++----练习--bool类型作为特别的int要区别对待
    C++----练习--while求和
    C++----练习
    mysql----二进制包安装
    linux----ulimit 限制
    python----特性003
    python----特性002
  • 原文地址:https://www.cnblogs.com/wxquare/p/4803753.html
Copyright © 2011-2022 走看看