数组中的逆序对
来源:互联网 发布:listing优化 编辑:程序博客网 时间:2024/06/05 04:20
1.题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
传送门
2.code(java1.7版本)
public class Solution { public long ans=0; public int InversePairs(int [] array) { if(array==null)return 0; int len=array.length; if(len==0)return 0; help(0,len-1,array); return (int)(ans%1000000007); } public void help(int left,int right,int[]array){ if(left==right)return; int mid=left+(right-left)/2; help(left,mid,array); help(mid+1,right,array); int len=right-left+1; int[]temp=new int[len]; int i=left; int j=mid+1; int k=0; while(i<=mid||j<=right){ if(i>mid){ temp[k]=array[j]; j++; k++; } else if(j>right){ temp[k]=array[i]; i++; k++; } else{ if(array[i]>array[j]){ ans=ans+mid-i+1; temp[k]=array[j]; j++; k++; } else{ temp[k]=array[i]; i++; k++; } } } k=0; for(i=left;i<=right;i++){ array[i]=temp[k]; k++; } }}
3.结题思路
我做的就是运用的归并排序的思想,就是对于归并排序的一个改进,把数据分成前后两个数组(递归分到每个数组仅有一个数据项),合并数组,合并时,出现前面的数组值array[i]大于后面数组值array[j]时;则前面数组array[i]~array[mid]都是大于array[j]的,ans+= mid+1 - i。这样归并完整个数组,也就完成了整个逆序对的计算。(打完收工)
阅读全文
0 0
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- <数据结构与算法>双向循环链表的全面基本框架(C语言描述)
- 分类xc
- spring boot入门(二)- 输出json对象
- MySQL tips
- linux中awk命令详解
- 数组中的逆序对
- Codeforces 359B Permutation
- Python3 数据类型
- Supervisord使用笔录
- Java 编程思想(八)BIO/NIO/AIO的具体实现
- fscanf 函数详解
- 常见排序算法——七大比较类排序算法(Seven Most Common Sorting Algorithm)
- try-catch中的return的问题
- 1038. 统计同成绩学生(20)