@@ -128,6 +128,8 @@ class Solution {
128128 }
129129
130130public:
131+ /*
132+ // slower, need to find lower_bound
131133 int reversePairs(vector<int>& nums) {
132134 int result = 0;
133135 if(nums.empty()) {
@@ -144,38 +146,68 @@ class Solution {
144146 }
145147 return result;
146148 }
149+ */
150+
151+ // faster
152+ int reversePairs (vector<int >& nums) {
153+ int result = 0 ;
154+ if (nums.empty ()) {
155+ return result;
156+ }
157+ int n = (int )nums.size ();
158+ vector<pair<int , int >> data (n);
159+ for (int i = 0 ; i < n; i++) {
160+ data[i] = {nums[i], i};
161+ }
162+ sort (data.begin (), data.end ());
163+ SegmentTree segmentTree;
164+ segmentTree.init (n);
165+ for (int i = 0 , k = 0 ; i < n; i++) {
166+ while (k < n and 2LL * data[k].first < data[i].first ) {
167+ segmentTree.insert (data[k++].second );
168+ }
169+ result += segmentTree.query (data[i].second + 1 , n - 1 );
170+ }
171+ return result;
172+ }
147173};
148174
149175// BIT (AC)
150176class Solution {
151- void update (vector<int >& BIT, int index) {
152- while (index > 0 ) {
153- BIT[index]++;
154- index -= index & (-index);
177+ vector<int > tree;
178+ int n;
179+
180+ void update (int indx, int value) {
181+ while (indx <= n) {
182+ tree[indx] += value;
183+ indx += (indx & -indx);
155184 }
156185 }
157186
158- int query (vector< int >& BIT, int index ) {
187+ int query (int indx ) {
159188 int sum = 0 ;
160- while (index < BIT. size () ) {
161- sum += BIT[index ];
162- index += index & (-index );
189+ while (indx > 0 ) {
190+ sum += tree[indx ];
191+ indx -= (indx & -indx );
163192 }
164193 return sum;
165194 }
166195
167196public:
168197 int reversePairs (vector<int >& nums) {
169- int n = nums.size ();
170- vector<int > numsCopy (nums);
171-
172- sort (numsCopy.begin (), numsCopy.end ());
173-
174- vector<int > BITS (n + 1 , 0 );
175- int count = 0 ;
198+ this ->n = nums.size ();
199+ vector<pair<int , int >> data (n);
176200 for (int i = 0 ; i < n; i++) {
177- count += query (BITS, lower_bound (numsCopy.begin (), numsCopy.end (), 2LL * nums[i] + 1 ) - numsCopy.begin () + 1 );
178- update (BITS, lower_bound (numsCopy.begin (), numsCopy.end (), nums[i]) - numsCopy.begin () + 1 );
201+ data[i] = {nums[i], i + 1 };
202+ }
203+ sort (data.begin (), data.end ());
204+ tree = vector<int >(n + 1 , 0 );
205+ int count = 0 ;
206+ for (int i = 0 , k = 0 ; i < n; i++) {
207+ while (k < n and 2LL * data[k].first < data[i].first ) {
208+ update (data[k++].second , 1 );
209+ }
210+ count += query (n) - query (data[i].second );
179211 }
180212 return count;
181213 }
0 commit comments