剑指offer(32)-数组中的逆序对
来源:互联网 发布:linux 70秒漏洞 编辑:程序博客网 时间:2024/06/05 00:57
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
代码
class Solution {public: int count = 0; int InversePairs(vector<int> data){ int length = data.size(); return mergeSort(data, 0, length-1); } int mergeSort(vector<int>& data, int start, int end) { // 递归终止条件 if(start >= end) { return 0; } // 递归 int mid = (start + end) / 2; int leftCounts = mergeSort(data, start, mid); int rightCounts = mergeSort(data, mid+1, end); // 归并排序,并计算本次逆序对数 vector<int> copy(data); // 数组副本,用于归并排序 int foreIdx = mid; // 前半部分的指标 int backIdx = end; // 后半部分的指标 int counts = 0; // 记录本次逆序对数 int idxCopy = end; // 辅助数组的下标 while(foreIdx>=start && backIdx >= mid+1) { if(data[foreIdx] > data[backIdx]) { copy[idxCopy--] = data[foreIdx--]; counts += backIdx - mid; } else { copy[idxCopy--] = data[backIdx--]; } } while(foreIdx >= start) { copy[idxCopy--] = data[foreIdx--]; } while(backIdx >= mid+1) { copy[idxCopy--] = data[backIdx--]; } for(int i=start; i<=end; i++) { data[i] = copy[i]; } return (leftCounts+rightCounts+counts); }};
0 0
- 数组中的逆序对(剑指offer)
- 剑指offer(32)-数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer 36 数组中的逆序对
- 剑指offer--数组中的逆序对
- 剑指Offer之 - 数组中的逆序对
- 剑指offer之数组中的逆序对
- 剑指offer 36 - 数组中的逆序对
- 《剑指offer》数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer—数组中的逆序对
- 【剑指offer】之数组中的逆序对
- 剑指offer:数组中的逆序对
- [剑指offer]数组中的逆序对
- 剑指offer:数组中的逆序对
- 剑指Offer--036-数组中的逆序对
- [剑指offer]数组中的逆序对
- 《剑指offer》:[36]数组中的逆序对
- 扯淡C++设计模式之一 [ 三种工厂模式 ]
- 移动端web开发,click touch tap区别
- 第16周 范型程序补充之set用法
- 支付宝在线付款的校验和异步通知
- camel 路由跳转组件使用
- 剑指offer(32)-数组中的逆序对
- All consistent reads within the same transaction read the snapshot established by the first read.
- HDU 2187 悼念512汶川大地震遇难同胞——老人是真饿了
- 第四十讲 项目5 张三、李四、王五、刘六的年龄等差问题
- IOS开源框架SJFramework-设计过程
- 4-2 顺序表操作集 (20分)
- 535 5.7.8 Error: authentication failed: generic failure
- NYOJ 592 spiral grid (BFS)
- Crosswalk Project for Android