How to find the maximum number of pairs having difference less than a particular value?

前端 未结 1 822
情深已故
情深已故 2021-01-22 02:26

I am given two arrays (can contain duplicates and of same length) containing positive integers. I have to find the maximum number of pairs that have absolute difference less tha

相关标签:
1条回答
  • 2021-01-22 03:13

    The usual idea is to loop over sorted ranges. This, you can bring down the brute-force O(N^2) effort to usually O(N log N).

    Here is an algorithm for that in pseudo code (maybe I'll update later with real C++ code):

    • Sort both arrays
    • Loop over both simultaneously with two iterators:
      1. If a pair is found insert it into your list. Increase both iterators.
      2. Otherwise, increase the indicator pointing to the smaller element.

    In total, this is dominated by the sort which on average takes O(N log N).


    Here is the promised code:

    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;
    }
    

    It returns the matching elements of the two vectors as a vector of std::pairs. For your example, it prints

    3  8
    4  9
    

    DEMO

    0 讨论(0)
提交回复
热议问题