剑指Offer_35_数组中的逆序对
来源:互联网 发布:星际争霸 for mac 编辑:程序博客网 时间:2024/06/04 17:56
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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
解题思路
利用归并排序的思想,每次排序相邻两段的数据并统计逆序,相对于前后的数据段之间没有相对数据没有改变。
实现
public class Solution { public int InversePairs(int [] array) { if(array == null || array.length <= 1) return 0; int[] copy = new int[array.length]; for (int i =0; i < array.length; i++){ copy[i] = array[i]; } return mergerCount(array, copy, 0, array.length-1); } private int mergerCount(int[] array, int[] copy, int start, int end) { if (start >= end){ if (start == end) copy[start] = array[start]; return 0; } int mid = (start + end) / 2; int c1 = mergerCount(copy, array, start, mid); int c2 = mergerCount(copy, array, mid + 1, end); int count = 0; int l = mid; int r = end; int index = end; while (r > mid && l >= start){ if (array[r] >= array[l]){ copy[index--] = array[r--]; }else { //前面的当前值大于后面的当前值,那么前面的当前值大于后面剩余部分,都是逆序对 count += r - mid; copy[index--] = array[l--]; if (count >= 1000000007) count %= 1000000007; } } while (r > mid) copy[index--] = array[r--]; while (l >= start) copy[index--] = array[l--]; return (count + c1 + c2) % 1000000007; }}
0 0
- 剑指Offer_35_数组中的逆序对
- 剑指offer_数组---数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- Java方法
- Android内存优化
- 51nod oj 1420 数袋鼠好有趣【贪心】
- Java IO系列(五):读写对象ObjectOutputStream和ObjectInputStream
- AlertDialog 错误
- 剑指Offer_35_数组中的逆序对
- Parameter index out of range (1 > number of parameters, which is 0).
- hdu4771 Stealing Harry Potter’s Precious(状态压缩+bfs)
- 交换机相关总结
- 《数据结构与算法》学习笔记13 单链表和双端链表
- hadoop2.X 伪分布安装
- java.net.BindException: Address already in use: JVM_Bind
- 关于性能优化的总结
- Android Studio ADB 环境变量配置