数组中的逆序对(数组)
来源:互联网 发布:6s 拍人 知乎 编辑:程序博客网 时间:2024/05/21 13:32
题目描述:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
思路:
归并排序的改进,把数据分成前后两个数组(递归分到每个数组仅有一个数据项),合并数组,合并时,出现前面的数组值arr[i]大于后面数组值arr[j]时,则前面数组arr[i]~arr[mid]都是大于array[j]的,cnt += mid+1 - i。
测试用例输出结果比较大,对每次返回的count mod(1000000007)求余
(这种写法超时,每次递归申请数组耗时)
public class Solution { public static void main(String[] args) { Solution s = new Solution(); int[] arr = {1,2,3,4,5,6,7,0}; int[] arr2 = {4,3,2,1}; System.out.println(s.InversePairs(arr)); //输出:7 System.out.println(s.InversePairs(arr2)); //输出:6 } public int InversePairs(int [] array) { if (array != null) return MSort(array, 0, array.length - 1); return 0; } private int MSort(int[] arr, int start, int end) { if (start >= end) return 0; int mid = start + (end - start) / 2; int left = MSort(arr, start, mid) % 1000000007; int right = MSort(arr, mid + 1, end) % 1000000007; int cnt = 0; int[] tmp = new int[end - start + 1]; int i = start; int j = mid + 1; int k = 0; while (i <= mid && j <= end) { if (arr[i] < arr[j]) tmp[k++] = arr[i++]; else { tmp[k++] = arr[j++]; cnt = (cnt + mid - i + 1) % 1000000007; } } while (i <= mid) tmp[k++] = arr[i++]; while (j <= end) tmp[k++] = arr[j++]; for (k = 0; k < tmp.length; k++) arr[start + k] = tmp[k]; return (cnt + left + right) % 1000000007; }}
改进的写法不超时:
public class Solution { public int InversePairs(int [] array) { int[] copy = new int[array.length]; for (int i = 0; i < array.length; i++) copy[i] = array[i]; if (array != null) return MSort(array, copy, 0, array.length - 1); return 0; } private int MSort(int[] arr, int[] copy, int start, int end) { if (start >= end) return 0; int mid = (end + start) >> 1; int left = MSort(arr, copy, start, mid) % 1000000007; int right = MSort(arr, copy,mid + 1, end) % 1000000007; int cnt = 0; int i = start; int j = mid + 1; int locCopy = start; while (i <= mid && j <= end) { if (arr[i] < arr[j]) copy[locCopy++] = arr[i++]; else { copy[locCopy++] = arr[j++]; cnt = (cnt + mid - i + 1) % 1000000007; } } while (i <= mid) copy[locCopy++] = arr[i++]; while (j <= end) copy[locCopy++] = arr[j++]; for (int k = start; k <= end; k++) arr[k] = copy[k]; return (cnt + left + right) % 1000000007; }}
阅读全文
0 0
- 数组中的逆序对(数组)
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 指针
- ios 为APP设置App Store中的兼容性问题
- centos7 安装GNOME 使用vnc连接
- Java Servlet初学(三)
- 使用git将项目上传到github(最简单方法)
- 数组中的逆序对(数组)
- java/android的链式写法
- JS——闭包(面试题)
- 在ngx-Datatable的onSelect方法中,this.selected使用patchValue方法为表单赋值注意事项
- VHDL总结
- spring源码分析,重新认识spring六(从new FileSystemXmlApplicationContext 开始解读)
- 论文阅读:Salient Object Detection: A Benchmark
- App Store 审核指南
- 阶乘之和