How to match a list of bounds with a list of numbers, one-to-one

Viewed 121

The task

I am solving a leetcode style task. Find the amout of values, that can be sortet into a bound (lower <= value <= upper).

Input: first line contains n & m, the amout of bounds and the amount of values. The second line contains the n lower bounds. The third line contains the n upper bounds. The fourth line contains m the values. (A single bound is li and ri)

Now find the amout of Values, that can be sorted into the bounds, if we do it optimally. (and output it)

Note: Each value can only be assigned one bound and one bound only to one value.

Ex. Input:

3 4
1 7 3
4 9 8
5 2 9 2

outputs 3.

My solution

I have a struct for the bounds:

struct Bounds {
    int min, max;
    // operator for sorting both primary and secondary keys
    bool operator < (const Bounds& rhs) const
    {
        if ( min == rhs.min )
            return max > rhs.max;
        else
            return min > rhs.min;
    }
};

and solve as follows:

int main()
{   
    int n, m, rval = 0;
    cin >> n >> m;
    Bounds newBound = {0, 0};
    vector<Bounds> bounds(n, newBound);
    vector<int> values(m);

    // get input
    for (int i = 0; i < n; i++)
        cin >> bounds[i].min;
    for (int i = 0; i < n; i++)
        cin >> bounds[i].max;
    for (int i = 0; i < m; i++)
        cin >> values[i];

    // sort Bounds in descending order by lower bound as primary and upper bound as secondary
    std::sort(bounds.begin(), bounds.end(), less<Bounds>());
    //sort values in ascending order
    std::sort(values.begin(), values.end(), greater<int>());

    // for every bound 
    for (int j = 0; j < m; j++) {
        int value = values[j];
        for (int i = 0; i < bounds.size(); i++)
        {
            if (bounds[i].min <= value && value <= bounds[i].max) {
                rval++;
                bounds.erase(bounds.begin() + i);
                break;
            }
        }
    }

    cout << rval << "\n";
}

My Problem

This works, but:

  1. I don't think this is the optimal solution,
  2. It's to slow, as one Testcase with 10^6 values takes ~7 minutes to solve.

How can I improve it? Or should I scrap this approach?

I think my solution has 0(n^2 + (n log(n)))

Or Phrased differently: How can I remove the nested for loop?

0 Answers
Related