For an array A, if i < j, and A [i] > A [j], called (A [i], A [j]) is a reverse pair.
return total of reverse pairs in A.
Example
Given A = [2, 4, 1, 3, 5] , (2, 1), (4, 1), (4, 3) are reverse pairs. return 3
這道題跟LeetCode上的那道Count of Smaller Numbers After Self是一樣的,唯一的一點點的小區別是那道題是返回一個向量,表示出原數組中每一個數字的右邊比其小的數的個數,而這道題讓我們求翻轉對的總數,其實就是把每個數字右邊比其小的數的個數都加起來即可,具體講解請參加之前那篇博客Count of Smaller Numbers After Self,參見代碼如下;
class Solution { public: long long reversePairs(vector<int>& A) { long long res = 0; vector<int> v; for (int i = A.size() - 1; i >= 0; --i) { int left = 0, right = v.size(); while (left < right) { int mid = left + (right - left) / 2; if (A[i] > v[mid]) left = mid + 1; else right = mid; } v.insert(v.begin() + right, A[i]); res += right; } return res; } };
