码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode3

时间:2015-09-12 23:43:12      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:

//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

leetCode3

标签:

原文地址:http://www.cnblogs.com/wxquare/p/4803753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!