剑指offer 36. 数组中的逆序对
来源:互联网 发布:中兴网络机顶盒怎么样? 编辑:程序博客网 时间:2024/05/22 04:18
//题目:输入一个数组,返回数组中的逆序数对个数//采用类似二路归并排序的方式来计算,每次出现第二组的数小于第一组数时就将result加上第一组元素的长度public class Main {public static void main(String[] args) throws Exception {System.out.println(findReverseCount(new int[]{7,5,6,4}));}public static int findReverseCount(int[] input){int low = 0;int high = input.length-1;int result = sort(input,low,high);return result;}public static int sort(int[] input, int low, int high){if(low == high){//当low与high相等时就返回0return 0;}int mid = (low+high)/2;int left = sort(input,low,mid);//要返回每一组归并的逆序数int right = sort(input,mid+1,high);int count = merge(input,low,high,mid);return left+right+count;}public static int merge(int[] input, int low, int high, int mid){int result = 0;int[] temp = new int[input.length];for(int i = low;i<=high;i++){temp[i] = input[i];}int leftStart = low;int leftEnd = mid;int rightStart = mid+1;int rightEnd = high;int index = low;while(leftStart<=leftEnd && rightStart<=rightEnd){if(temp[leftStart]>temp[rightStart]){//第二组的第一个数小于第一组第一个数input[index] = temp[rightStart];result = result+(leftEnd-leftStart+1);//逆序数加上第一组还剩元素的个数rightStart++;}else{input[index] = temp[leftStart];leftStart++;}index++;}while(leftStart<=leftEnd){input[index] = temp[leftStart];leftStart++;index++;}while(rightStart<=rightEnd){input[index] = temp[rightStart];rightStart++;index++;}return result;}}
0 0
- 剑指offer 36. 数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer 36 数组中的逆序对
- 剑指offer--数组中的逆序对
- 剑指Offer之 - 数组中的逆序对
- 剑指offer之数组中的逆序对
- 剑指offer 36 - 数组中的逆序对
- 《剑指offer》数组中的逆序对
- 【剑指offer】数组中的逆序对
- 剑指offer—数组中的逆序对
- 【剑指offer】之数组中的逆序对
- 剑指offer:数组中的逆序对
- [剑指offer]数组中的逆序对
- 剑指offer:数组中的逆序对
- 剑指Offer--036-数组中的逆序对
- [剑指offer]数组中的逆序对
- 《剑指offer》:[36]数组中的逆序对
- 《剑指offer》-数组中的逆序对
- 对象工具
- Qt学习笔记 数据类型转换
- 单例的几种写法
- 爱因斯坦犯了什么错?
- mysql 查询数据库中第n大数据的值
- 剑指offer 36. 数组中的逆序对
- (git简单教程)使用git命令上传本地项目到github项目
- IntelliJ IDEA 提交代码到 GitHub
- SNMP协议详解<二>
- 庆科emw3162wifi模块作wedserver简单介绍
- ZeroMQ初探
- 基于JFinal建立的Db+Record实现的数据库表字段加密
- UIViewContentMode各类型效果
- 有关素数