From b66af58533107a32df9c92f60cc0714e50c80d66 Mon Sep 17 00:00:00 2001 From: rahullkr Date: Tue, 12 Dec 2023 01:23:41 +0530 Subject: [PATCH 1/2] added new file in c++ repo --- C++/Reverse_pair.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 C++/Reverse_pair.cpp diff --git a/C++/Reverse_pair.cpp b/C++/Reverse_pair.cpp new file mode 100644 index 00000000..8086eafc --- /dev/null +++ b/C++/Reverse_pair.cpp @@ -0,0 +1,58 @@ +class Solution { +public: + int pairCount = 0; + + void merge(vector& 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 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& 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& nums) { + mergeSort(nums, 0, nums.size() - 1); + return pairCount; + } +}; From 4c0fd9b08d44752f1f421b0c797d13487b08446b Mon Sep 17 00:00:00 2001 From: rahullkr Date: Tue, 12 Dec 2023 01:34:16 +0530 Subject: [PATCH 2/2] updated readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b2cac739..99853854 100644 --- a/README.md +++ b/README.md @@ -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 | | |