数组中的逆序对
来源:互联网 发布:编程一小时网站 编辑:程序博客网 时间:2024/06/07 19:36
有一组数,对于其中任意两个数组,若前面一个大于后面一个数字,则这两个数字组成一个逆序对。请设计一个高效的算法,计算给定数组中的逆序对个数。
给定一个int数组A和它的大小n,请返回A中的逆序对个数。保证n小于等于5000。
测试样例:
[1,2,3,4,5,6,7,0],8
返回:7
import java.util.*;
public class AntiOrder {private int res = 0;
public int count(int[] A, int n) {
if(n>0){
int[] B= new int[n];
merge(A, 0, n - 1, B);
}
return res;
}
public void merge(int[] A,int low, int high,int[] B) {
if(low<high){
int mid = low + ((high-low)>>1);
merge(A,low,mid,B);
merge(A,mid+1,high,B);
mergeSort(A,low,mid,high,B);
}
}
private void mergeSort(int[] a, int low, int mid, int high, int[] b) {
int i = mid;
int j = high;
int index = high;
while(i>=low&&j>mid){
if(a[i]>a[j]){
res+=j-mid;
b[index--] = a[i--];
}else{
b[index--] = a[j--];
}
}
while(i>=low){
b[index--] = a[i--];
}
while(j>mid){
b[index--] =a[j--];
}
for(int t=high;t>=low;t--){
a[t] = b[t];
}
}
}
题目来源:数组中的逆序对
0 0
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 数组中的逆序对
- 342. Power of Four
- 换yum源
- Cocos2d-x开发系列 交叉开发模式五 绑定C++对象到Lua
- SPI详解
- Java基础——super的几种用法并与this的区别
- 数组中的逆序对
- AngularJS学习环境配置
- 对于java学习中的date与String转换demo
- iOS的图片拉伸方法
- DBMS_REDEFINITION子程序概要
- HDOJ_A hard puzzle
- xcode 中#pragma得使用
- 新建iOS工程如何给所有类名添加前缀
- 经验分享之使用vagrant安装linux虚拟机