LintCode 1635: Max Pair (Binary Search 经典题)

原题如下:
1635. Max Pair
Give two Lists, give a maximum value, find a bunch in each of the two lists, and find all the pairs that are closest to the maximum but not larger than the maximum.

Example
Give a=[2,3,4,5,6], b=[4,5,7], x=8’, return [[3,5],[4,4]].

Explanation:
the sum of [3,5] or [4,4] is 8, which is no larger than 8.
Give a=[2,3,4,5,6], b=[4,5,7], x=10’, return [[3,7],[5,5],[6,4]].

Explanation:
the sum of [3,7],[5,5],[6,4] is 10, which is no larger than 10.
Notice
The length of the two lists do not exceed 100000100000.
Each element do not exceed 10000000001000000000.

解法1:
用Binary Search。我的方法较慢。

class Solution {
public:
    /**
     * @param a: the first list
     * @param b: the second list
     * @param x: the max sum
     * @return: the pairs whose sum are not exceed x
     */
    vector<vector<int>> getAns(vector<int> &a1, vector<int> &b1, int x) {
        set<int> sa(a1.begin(), a1.end());
        set<int> sb(b1.begin(), b1.end());
        a1.assign(sa.begin(), sa.end());
        b1.assign(sb.begin(), sb.end());
        
        vector<vector<int>> result;
        int maxSum = INT_MIN;
        bool targetFind = false;
        for (auto n : a1) {
            std::vector<int>::iterator lowIt = std::lower_bound(b1.begin(),  b1.end(), x - n);
            
            if ((lowIt!= b1.begin()) && ((n + *lowIt) > x)) lowIt--;   //as *lowIt >= (x-n)
            
            int m = *lowIt; 
            int sum = n + m;
            if (sum > x) 
                continue;
            else if (sum == x) {
                if (maxSum < sum) {
                    result = {};
                    maxSum = sum;
                }
                targetFind = true;
                result.push_back({n, m});
            } else if (!targetFind) {
                if (sum > maxSum) {
                    result = {};
                    maxSum = sum;
                    result.push_back({n, m});
                }
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值