题解 | #数组中的逆序对#
数组中的逆序对
http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5
class Solution {
public:
int find(vector<int> vec, int target) {
int l = 0, r = vec.size() - 1;
while(l < r) {
int mid = (l + r) / 2;
if(target > vec[mid])
l = mid + 1;
else
r = mid;
}
return l;
}
int InversePairs(vector<int> data) {
int res = 0;
int n = data.size();
if( n < 2)
return res;
vector<int> temp;
temp.push_back(data[n-1]);
for(int i = n - 2; i >= 0; i--) {
int index = find(temp, data[i]);
if(data[i] > temp[index]) {
res += (index + 1);
res = res % 1000000007;
temp.insert(temp.begin() + index + 1, data[i]);
}else {
res += index ;
res = res % 1000000007;
temp.insert(temp.begin() + index, data[i]);
}
}
return res;
}
};