剑指offer 数组中的逆序对
来源:互联网 发布:mac c语言编程软件 编辑:程序博客网 时间:2024/06/01 18:55
题目:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
示例1
输入
1,2,3,4,5,6,7,0
输出
7
这个题目如果直接暴力做,那么复杂度是O(n^2),那么会超时。
思路:其实是归并排序的思想,首先来看一张图,
其实可以进行两两归并排序,然后在向上传的时候进行合并逆序对,其实跟线段树的思想特别像,例如,在叶子节点7 8 时候,因为8>7 故逆序对数量为1,同理6>5则逆序对数量也为1,然后上层的(8 7 )(6 5 )合并向上传的时候,因为7>6 7>5 则增加2对逆序对,同理8>6 8>5 故总共2+2+2=6对逆序对在(8,7,6,5)这个节点。可以节省时间的原因是在递归过程中减少了比较次数,因为例如8>6 ,那么必定>5,所以两个指针只需要一趟扫描就行。
代码如下:
class Solution {public: int InversePairs(vector<int> data) { int len = data.size(); if(len<=0) return 0; vector<int> temp(data); return mergeSort(data,temp,0,len-1); } int mergeSort(vector<int> &array,vector<int> &temp,int start,int end) { if(start==end) return 0; int mid = (start+end)>>1; int leftNum = mergeSort(temp,array,start,mid); int rightNum = mergeSort(temp,array,mid+1,end); int cnt = end; int mid_l = mid; int mid_r = end; int sum = 0; //逆序对的数量 while(mid_l>=start&&mid_r>=mid+1) { if(array[mid_l]>array[mid_r]) { temp[cnt--] = array[mid_l--]; sum+=(mid_r-mid); if(sum>1000000007) sum%=1000000007; } else temp[cnt--] = array[mid_r--]; } while(mid_r>=mid+1) temp[cnt--] = array[mid_r--]; while(mid_l>=start) temp[cnt--] = array[mid_l--]; return (leftNum+rightNum+sum)%1000000007; }};
阅读全文
0 0
- 【剑指offer】数组中的逆序对
- 剑指offer 36 数组中的逆序对
- 剑指offer--数组中的逆序对
- 剑指Offer之 - 数组中的逆序对
- 剑指offer之数组中的逆序对
- 剑指offer 36 - 数组中的逆序对
- 《剑指offer》数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer—数组中的逆序对
- 【剑指offer】之数组中的逆序对
- 剑指offer:数组中的逆序对
- [剑指offer]数组中的逆序对
- 剑指offer:数组中的逆序对
- 剑指Offer--036-数组中的逆序对
- [剑指offer]数组中的逆序对
- 《剑指offer》:[36]数组中的逆序对
- 《剑指offer》-数组中的逆序对
- 数组中的逆序对(剑指offer)
- Mybatis原生dao开发方法实现增删改查
- ADV-98-约数个数
- 密码学基础
- Linux运维学习笔记之七:定时任务crond 服务
- DFS判断有无环
- 剑指offer 数组中的逆序对
- Mybatis mapper代理开发方法实现增删改查
- mysql5.7官网直译SQL语句优化--IS NULL查询优化
- hive中order by,sort by, distribute by, cluster by作用以及用法
- Docker 学习
- ADV-15-最大乘积
- 面向对象五大原则、三大特征
- 解决BackBox中Fcitx输入法中文输入状态下不显示候选词框的问题
- C语言中控制输出格式