Given an integer array nums, return the number of reverse pairs in the array.
A reverse pair is a pair (i, j) where:
0 <= i < j < nums.length andnums[i] > 2 * nums[j].Input: nums = [1,3,2,3,1]
Output: 2
Explanation: The reverse pairs are:
(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1
Input: nums = [2,4,3,5,1]
Output: 3
Explanation: The reverse pairs are:
(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1
(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1
The problem asks us to count the number of important reverse pairs (i, j) such that i < j and nums[i] > 2 * nums[j]. A straightforward approach is to evaluate every possible pair (i, j) and check the condition. This leads to a simple double loop solution.
(i, j) where i < j.nums[i] > 2 * nums[j].n is the number of elements in nums. We check each pair (i, j) once.The brute-force solution is inefficient for large inputs. By using a modified version of merge sort, we can efficiently count reverse pairs. The essential insight is to leverage the sorted order of the array to count pairs more efficiently.
n is the number of elements in nums. This includes splitting the array (log n levels) and merging subarrays (O(n) per level).