剑指offer-面试题36-数组中的逆序对
来源:互联网 发布:男生丁丁知乎 编辑:程序博客网 时间:2024/06/11 03:32
/** * Created by apple on 17/6/2. * 求数组中的逆序对数,时间复杂度为O(nlogn) */public class InversePairs { public static void main(String[] args) { int[] arr = {7, 4, 5, 6, 1, 2}; System.out.println("排序之前的数组:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.println("逆序对数为:" + getInversePairs(arr)); System.out.println("排序之后的数组:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } /** * 获取逆序对数量,通过归并的方法,时间复杂度O(nlogn) * * @param arr,带查找的逆序对的数组 * @return arr中逆序对的个数 */ public static int getInversePairs(int[] arr) { if (arr == null || arr.length <= 0) { return -1; } return getInversePairsCore(arr, 0, arr.length - 1); } private static int getInversePairsCore(int[] arr, int low, int high) { if (low >= high) { return 0; } int middle = (low + high) / 2; int left = getInversePairsCore(arr, low, middle); int right = getInversePairsCore(arr, middle + 1, high); int count = getTwoArrPairs(arr, low, middle, high); return left + right + count; } private static int getTwoArrPairs(int[] arr, int low, int middle, int high) { int[] copy = new int[arr.length]; int index = high; int countPairs = 0; int endL = middle; int endR = high; //统计左数组和右数组的逆序对数,并拼接 while (low <= endL && middle + 1 <= endR) { if (arr[endL] > arr[endR]) { countPairs += endR - middle; copy[index--] = arr[endL--]; } else if (arr[endL] <= arr[endR]) { copy[index--] = arr[endR--]; } } //拼接剩余的数 while (endR >= middle + 1) { copy[index--] = arr[endR--]; } while (endL >= low) { copy[index--] = arr[endL--]; } //修改原数组 for (int i = low; i <= high; i++) { arr[i] = copy[i]; } //返回两个数组的逆序对数 return countPairs; }}
阅读全文
0 0
- 剑指offer面试题36:数组中的逆序对
- [剑指offer][面试题36]数组中的逆序对
- 【剑指offer】面试题36:数组中的逆序对
- 剑指Offer:面试题36 数组中的逆序对
- 剑指offer 面试题36:数组中的逆序对
- 剑指offer 面试题36—数组中的逆序对
- 【剑指Offer学习】【面试题36:数组中的逆序对】
- 剑指offer-面试题36:数组中的逆序对
- 剑指offer之面试题36数组中的逆序对
- 剑指offer面试题36-数组中的逆序对
- 剑指offer面试题36:数组中的逆序对
- 剑指Offer----面试题36:数组中的逆序对
- 剑指Offer面试题36:数组中的逆序对
- 剑指offer--面试题36:数组中的逆序对
- 剑指Offer之面试题36:数组中的逆序对
- 剑指Offer---面试题36:数组中的逆序对
- 【剑指offer】面试题36-数组中的逆序对
- 剑指offer-面试题36-数组中的逆序对
- Struts2标签:checkboxlist
- css-零散知识点
- 机器学习算法中文视频教程
- OLE操作Excel(OLE/COM)
- 用CocoaPods 建立自己的库类
- 剑指offer-面试题36-数组中的逆序对
- 使用spring+redis实现缓存
- 关于bind的问题
- [LeetCode] Unique Paths II
- js try catch
- Java还要再学一遍基础(六)ArrayList详解
- Android 屏幕旋转 Sensor SensorManager
- 支持向量机通俗导论(理解SVM的三层境界)
- Codeforces 812C Sagheer and Nubian Market[二分]