【问题标题】:To reduce the time complexity [duplicate]为了降低时间复杂度[重复]
【发布时间】:2015-09-06 15:46:25
【问题描述】:

我有一个问题,我得到一组值 SET A 和一组值 SET B。我应该找到可能的最大对数,从集 A 中获取一个值,在集 B 中获取一个值. 健康)状况- 两个值之差应小于 11。

例如- SET A-2,3,4 套装 B-14,12,250 可能的最大对 - (14,4) 和 (12,3) 注意-(12,4) 也可以是一对,但它不会给我们最大可能的集合,因为会剩下 3 个。因此,两个达到最大 4 对,14 和 12 和 3。

我能够以 O(n^2) 复杂度解决这个问题,我正在寻找更好的解决方案。

【问题讨论】:

    标签: c++ dynamic-programming divide-and-conquer


    【解决方案1】:

    我在 10 分钟前回复了 similar question。这里的 ide 是一样的:循环 sorted 范围。

    这是与适用于您的问题的其他答案相同的代码(我只是用小于关系替换了相等性):

    auto find_pairs(std::vector<int>& arr1, std::vector<int>& arr2, int diff)
    {
        std::vector<std::pair<int,int> > ret;
    
        std::sort(std::begin(arr1), std::end(arr1));
        std::sort(std::begin(arr2), std::end(arr2));
    
        auto it1= std::begin(arr1);
        auto it2= std::begin(arr2);
    
        while(it1!= std::end(arr1) && it2!= std::end(arr2))
        {
            if(std::abs(*it1-*it2) < diff)
            {
                ret.push_back(std::make_pair(*it1,*it2));
                ++it1;
                ++it2;
            }
            else if(*it1<*it2)
            {
                ++it1;
            }
            else
            {
                ++it2;
            }
        }
    
        return ret;
    }
    

    这是您的示例的应用程序,

    int main()
    {
    
        std::vector<int> arr1 = {2,3,4};   
        std::vector<int> arr2 = {14,12,250};   
        int diff=11;
    
        auto pairs = find_pairs(arr1, arr2, diff);
    
        for(auto& i : pairs)
        {
            std::cout<<i.first<<"  "<<i.second<<std::endl;
        }    
    }
    

    通过这个获得OP中给出的所需答案:

    2  12
    4  14
    

    DEMO.

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 2012-07-28
      • 2016-10-07
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      相关资源
      最近更新 更多