@@ -128,6 +128,8 @@ class Solution {
128
128
}
129
129
130
130
public:
131
+ /*
132
+ // slower, need to find lower_bound
131
133
int reversePairs(vector<int>& nums) {
132
134
int result = 0;
133
135
if(nums.empty()) {
@@ -144,38 +146,68 @@ class Solution {
144
146
}
145
147
return result;
146
148
}
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
+ }
147
173
};
148
174
149
175
// BIT (AC)
150
176
class 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);
155
184
}
156
185
}
157
186
158
- int query (vector< int >& BIT, int index ) {
187
+ int query (int indx ) {
159
188
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 );
163
192
}
164
193
return sum;
165
194
}
166
195
167
196
public:
168
197
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);
176
200
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 );
179
211
}
180
212
return count;
181
213
}
0 commit comments