Skip to content

Commit caac289

Browse files
committed
reverse pairs
1 parent 2e223c7 commit caac289

File tree

2 files changed

+81
-1
lines changed

2 files changed

+81
-1
lines changed

Striver Sheet/Day-3/Reverse Pairs.cpp

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
Reverse Pairs
3+
=============
4+
5+
Given an integer array nums, return the number of reverse pairs in the array.
6+
7+
A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
8+
9+
Example 1:
10+
Input: nums = [1,3,2,3,1]
11+
Output: 2
12+
13+
Example 2:
14+
Input: nums = [2,4,3,5,1]
15+
Output: 3
16+
17+
Constraints:
18+
1 <= nums.length <= 5 * 104
19+
231 <= nums[i] <= 231 - 1
20+
*/
21+
22+
class Solution
23+
{
24+
public:
25+
int merge(vector<int> &nums, int low, int mid, int high)
26+
{
27+
int count = 0;
28+
int i = low, j = mid + 1;
29+
30+
// count pairs
31+
while (i <= mid)
32+
{
33+
while (j <= high && nums[i] > 2LL * nums[j])
34+
j++;
35+
count += (j - (mid + 1));
36+
i++;
37+
}
38+
39+
// merge the sorted arrays
40+
vector<int> temp;
41+
i = low;
42+
j = mid + 1;
43+
44+
while (i <= mid && j <= high)
45+
{
46+
if (nums[i] < nums[j])
47+
temp.push_back(nums[i++]);
48+
else
49+
temp.push_back(nums[j++]);
50+
}
51+
52+
while (i <= mid)
53+
temp.push_back(nums[i++]);
54+
while (j <= high)
55+
temp.push_back(nums[j++]);
56+
57+
for (int k = low; k <= high; ++k)
58+
nums[k] = temp[k - low];
59+
60+
return count;
61+
}
62+
63+
int mergeSort(vector<int> &nums, int low, int high)
64+
{
65+
int count = 0;
66+
if (low < high)
67+
{
68+
int mid = (low + high) / 2;
69+
count += mergeSort(nums, low, mid);
70+
count += mergeSort(nums, mid + 1, high);
71+
count += merge(nums, low, mid, high);
72+
}
73+
return count;
74+
}
75+
76+
int reversePairs(vector<int> &nums)
77+
{
78+
return mergeSort(nums, 0, nums.size() - 1);
79+
}
80+
};

Striver Sheet/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
- [Majority Element](https://leetcode.com/problems/majority-element/) - [Cpp Soultion](./Day-3/Majority%20Element.cpp)
2828
- [Majority Element II](https://leetcode.com/problems/majority-element-ii/) - [Cpp Soultion](./Day-3/Majority%20Element%20II.cpp)
2929
- [Unique Paths](https://leetcode.com/problems/unique-paths/) - [Cpp Soultion](./Day-3/Unique%20Paths.cpp)
30-
- []() - [Cpp Soultion](./Day-3/.cpp)
30+
- [Reverse Pairs](https://leetcode.com/problems/reverse-pairs/) - [Cpp Soultion](./Day-3/Reverse%20Pairs.cpp)
3131

3232
###
3333

0 commit comments

Comments
 (0)