• 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

  • 相关阅读:
    SQLServer 系统表简介
    C# abstract 和 virtual 关键字
    Windows脚本 %~dp0的含义
    Windows脚本 批处理中能够使用的系统变量
    Windows脚本 Shift 命令
    Windows脚本 关于本机ARP静态绑定批处理文件讲解[绑定ipmac脚本详解]
    开学测试
    仓库管理系统
    读《人月神话》
    个人作业2
  • 原文地址:https://www.cnblogs.com/wxquare/p/4803753.html
Copyright © 2020-2023  润新知