25. Reverse Pairs

Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].

You need to return the number of important reverse pairs in the given array.

Example1:
Input: [1,3,2,3,1]
Output: 2

Example2:
Input: [2,4,3,5,1]
Output: 3

Solution:

Brute Force O(N^2)

class Solution
{
public:
    int reversePairs(vector<int> &nums)
    {
        int count = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = 0; j < nums.size(); j++)
            {
                if (i >= j)
                {
                    continue;
                }

                long long int a = nums[i];
                long long int b = 2 * (long long int)nums[j];
                
                if (a > b)
                {
                    count++;
                }
            }
        }
        return count;
    }
};

Solution: (Using Merge Sort)

Time Complexity: O(n log n)

Last updated

Was this helpful?