剑指offer:数组中的逆序对
class Solution {
public:
void solve(int x, int y, vector<int> &A, vector<int> &B, int &ans){//B为临时空间
if(y - x > 1){
int mid = x + (y - x)/2, left = x, right = mid, i = x;
solve(x, mid, A, B, ans);
solve(mid, y, A, B, ans);
int zuo = mid - x;
while(left < mid || right < y){
if(right >= y || (left < mid && A[left] < A[right]))
{B[i++] = A[left++];zuo--;}
else {B[i++] = A[right++];ans = (ans+zuo)00000007;}
}
}
for(int i = x; i < y; i++) A[i] = B[i];
}
int InversePairs(vector<int> data) {
vector<int> tmp = data;
int ans = 0;
solve(0, data.size(), data, tmp, ans);
return ans;
}
};
class Solution {
public:
void solve(int x, int y, vector<int> &A, vector<int> &B, int &ans){//B为临时空间
if(y - x > 1){
int mid = x + (y - x)/2, left = x, right = mid, i = x;
solve(x, mid, A, B, ans);
solve(mid, y, A, B, ans);
int zuo = mid - x;
while(left < mid || right < y){
if(right >= y || (left < mid && A[left] < A[right]))
{B[i++] = A[left++];zuo--;}
else {B[i++] = A[right++];ans = (ans+zuo)00000007;}
}
}
for(int i = x; i < y; i++) A[i] = B[i];
}
int InversePairs(vector<int> data) {
vector<int> tmp = data;
int ans = 0;
solve(0, data.size(), data, tmp, ans);
return ans;
}
};
2020-05-10
在牛客打卡31天,今天学习:刷题 5 道/代码提交 5 次
全部评论
相关推荐
点赞 评论 收藏
分享
![](https://static.nowcoder.com/fe/file/oss/1716965564844UEBJN.png)
![](https://static.nowcoder.com/fe/file/oss/1716965585666UBBME.png)
OPPO
| 校招
| 超多精选岗位
点赞 评论 收藏
分享
![](https://static.nowcoder.com/fe/file/oss/1716965564844UEBJN.png)
![](https://static.nowcoder.com/fe/file/oss/1716965585666UBBME.png)
OPPO
| 校招
| 超多精选岗位
点赞 评论 收藏
分享