Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions C++/Reverse_pair.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
class Solution {
public:
int pairCount = 0;

void merge(vector<int>& nums, int low, int mid, int high) {
int total = 0;
int i = low;
int j = mid + 1;
// Counting the number of pairs satisfying the condition nums[i] > 2 * nums[j]
while (i <= mid) {
while (j <= high && nums[i] > (long long)2 * nums[j]) {
j++;
}
total += (j - (mid + 1));
i++;
}

vector<int> temp;
i = low;
j = mid + 1;

while (i <= mid && j <= high) {
if (nums[i] < nums[j]) {
temp.push_back(nums[i++]);
} else {
temp.push_back(nums[j++]);
}
}

while (i <= mid) {
temp.push_back(nums[i++]);
}

while (j <= high) {
temp.push_back(nums[j++]);
}

for (int it = low; it <= high; it++) {
nums[it] = temp[it - low];
}

pairCount += total;
}

void mergeSort(vector<int>& nums, int low, int high) {
if (low < high) {
int mid = low + (high - low) / 2;
mergeSort(nums, low, mid);
mergeSort(nums, mid + 1, high);
merge(nums, low, mid, high);
}
}

int reversePairs(vector<int>& nums) {
mergeSort(nums, 0, nums.size() - 1);
return pairCount;
}
};
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
| # | Title | Solution | Time | Space | Difficulty | Tag | Tutorial |
| --- | --------------------------------------------------------------------------------------- | ------------------------------------------- | ------ | ------ | ---------- | --- | -------- |
| 973 | [K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | [C++](./C++/k-closest-points-to-origin.cpp) | _O(n)_ | _O(1)_ | Medium | | |
| 493 | [Reverse Pairs](https://leetcode.com/problems/reverse-pairs) | [C++](./C++/reverse_pair.cpp)
| _O(n log n)_ | _O(n)_ | Hard | | |

<br/>
<div align="right">
Expand Down