剑指offer|数组中的逆序对
来源:互联网 发布:语音输入翻译软件 编辑:程序博客网 时间:2024/06/06 02:04
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
思路:
使用归并排序算法的思想从下到上来做。
class Solution {public: int InversePairs(vector<int> data) { if(data.empty()) return 0; return mergeSort(data,0,data.size()-1); } int mergeSort(vector<int>& data, int begin, int end) { if(begin >= end) return 0; int mid= (end+begin)/2; int left=mergeSort(data,begin,mid); int right=mergeSort(data,mid+1,end); int count=0; vector<int> copy(data); int inxCopy=end; int inxLeft=mid; int inxRight=end; while(inxLeft>=begin && (inxRight>= mid+1)) { if(data[inxLeft]>data[inxRight]) { count += inxRight-mid; copy[inxCopy--]=data[inxLeft--]; } else { copy[inxCopy--]=data[inxRight--]; } } while(inxLeft>=begin) copy[inxCopy--]=data[inxLeft--]; while(inxRight >= mid+1) copy[inxCopy--]=data[inxRight--]; for(int i=begin;i<=end;++i) data[i]=copy[i]; return (count+left+right); }};
0 0
- 【剑指offer】数组中的逆序对
- 剑指offer 36 数组中的逆序对
- 剑指offer--数组中的逆序对
- 剑指Offer之 - 数组中的逆序对
- 剑指offer之数组中的逆序对
- 剑指offer 36 - 数组中的逆序对
- 《剑指offer》数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer—数组中的逆序对
- 【剑指offer】之数组中的逆序对
- 剑指offer:数组中的逆序对
- [剑指offer]数组中的逆序对
- 剑指offer:数组中的逆序对
- 剑指Offer--036-数组中的逆序对
- [剑指offer]数组中的逆序对
- 《剑指offer》:[36]数组中的逆序对
- 《剑指offer》-数组中的逆序对
- 数组中的逆序对(剑指offer)
- window.onresize获取窗口的变化
- Navicat for SQLite 索引是什么
- java连接mysql数据库批量的一点研究
- 对Web设计和开发人员有用的15个Chrome插件
- XML解析之DOM解析_四层结合数据库
- 剑指offer|数组中的逆序对
- iOS:导航条滚动透明度随着tableView的滚动而变化
- C语言哈希表 uthash
- Andorid生命周期实践
- Linux 系统启动时自动挂载文件
- Python logging模块学习
- Linux内核驱动基础(9)gpio的使用
- [译]Core Animation 3D介绍(第2部分)
- private,static,final和域对于重写覆盖方法的区别。