题目描述:

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007。

输入描述:

题目保证输入的数组中没有的相同的数字

数据范围:

对于%50的数据,size<=10^4

对于%75的数据,size<=10^5

对于%100的数据,size<=2*10^5

输入示例:

1,2,3,4,5,6,7,0

输出示例:

7

思路分析:

1. 最直接的想法,对于每个数,向后依次比较,计算每个数的逆序对。这样的复杂度是O(n^2),需要优化。

2. 利用空间换时间。利用归并排序的思想。参考:https://www.cnblogs.com/coffy/p/5896541.html,这样的时间复杂度就为O(nlogn)。

代码:

 class Solution {
public:
int InversePairs(vector<int> data) {
int length = data.size();
if (length <= )
return ; vector<int> copy;
for (int i = ; i<length; ++i)
copy.push_back(data[i]); long long count = InversePairsCore(data, copy, , length - );
return count % ;
} long long InversePairsCore(vector<int> &data, vector<int> &copy, int start, int end) {
if (start == end) {
copy[start] = data[start];
return ;
} int length = (end - start) / ; long long left = InversePairsCore(copy, data, start, start + length);
long long right = InversePairsCore(copy, data, start + length + , end); int i = start + length;
int j = end;
int indexCopy = end;
long long count = ;
while (i >= start && j >= start + length + ) {
if (data[i] > data[j]) {
copy[indexCopy--] = data[i--];
count += j - start - length;
}
else {
copy[indexCopy--] = data[j--];
}
} for (; i >= start; --i)
copy[indexCopy--] = data[i];
for (; j >= start + length + ; --j)
copy[indexCopy--] = data[j]; return count + left + right;
}
};
												

最新文章

  1. Scalaz(58)- scalaz-stream: fs2-并行运算示范,fs2 parallel processing
  2. [SDN] mininet walkthrough
  3. SILVERLIGHT&#160;多维表头、复杂表头&#160;MULTIPLE&#160;HEADER
  4. Windows Phone 8.1商店启动协议
  5. Vertica笔记
  6. SSDB 数据库如何换用 rocksdb 引擎?
  7. CCSpriteBatchNode的优化性能
  8. Node的Buffer
  9. bzoj1758 [Wc2010]重建计划 &amp; bzoj2599 [IOI2011]Race
  10. 基于Linux的oracle数据库管理 part5( linux启动关闭 自动启动关闭 oracle )
  11. Android源码学习之装饰模式应用
  12. android代码集锦
  13. Linux 部署 Tomcat和JDK
  14. LeetCode 笔记总结
  15. 2016/12/21 dplの课练
  16. CentOS 7下安装samba
  17. wget 网站扒取
  18. css经验之谈
  19. OpenCV——图像的矩(计算矩、轮廓面积、轮廓或曲线长度)
  20. c++官方文档-模版类

热门文章

  1. 【robotframework】pycharm+robotframe
  2. PB连接数据库
  3. java使用RSA与AES加密解密
  4. 注入 Istio sidecar
  5. 在CentOS 7上修改主机名的方法
  6. MAC地址IP地址网关地址
  7. SVN (TortioseSVN) 版本控制之忽略路径(如:bin、obj)
  8. debug版本的DLL调用release版本的DLL引发的一个问题
  9. c++中关联容器map的使用
  10. P2340 奶牛会展 DP 背包