Coursera Algorithms week3 归并排序 练习测验: Counting inversions
题目原文:
An inversion in an array a[] is a pair of entries a[i] and a[j] such that i<j but a[i]>a[j]. Given an array, design a linearithmic algorithm to count the number of inversions.
分析:
如果没有性能限制,用插入排序算法可以实现。题目性能被限制在nlogn,又是归并排序的练习题,很显然要实现个归并排序,并在里面计数。通过一个例子来看下计数方法,例如{6, 5, 2, 3, 4, 1}这个序列,归并过程中会分为分为如下几步:
1. 归并{6, 5},存在一次右侧元素5移至左侧的操作,变成{5, 6},归并前逆序对<6,5>
2. 归并{5, 6, 2},存在一次右侧元素2移至左侧的操作, 变成{2, 5, 6},归并前存在两对逆序对<5, 2>和<6, 2>
3. 归并{3, 4},不存在右侧元素左移操作
4. 归并{3, 4, 1},存在一次右侧元素1移至左侧的操作,变成{1, 3, 4},归并前存在两对逆序对<3, 1>和<4, 1>
5. 归并{2, 5, 6, 1, 3, 4},存在三次1、3、4右侧元素移至左侧的操作,归并前存在七对逆序对<2,1><5,1><6,1><5,3><6,3><5,4><6,4>
由上述分析可见,当右侧元素a[j]与左侧元素a[i]进行比较后需要移至左侧时,a[j]与区间 [ a[i] , a[mid] ]中的所有元素都可以组成逆序对,这个区间的元素个数为mid+1-i个。
因此代码如下:
import java.util.Arrays; /**
* @author evasean www.cnblogs.com/evasean/
*/
public class CountInversions {
private static Comparable[] aux;
private static int num = 0; // 逆序对计数 private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
} public static int inversionsNum(Comparable[] a) {
aux = new Comparable[a.length];
sort(a, 0, a.length - 1);
return num;
} private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo)
return;
int mid = lo + (hi - lo) / 2;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
} private static void merge(Comparable[] a, int lo, int mid, int hi) {
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
for (int k = lo; k <= hi; k++) {
if (i > mid) // i>mid表示aux的左半侧已经被全部被放于a中,直接将右半侧部分放入a
a[k] = aux[j++];
else if (j > hi) // j>hi表示aux的右半侧已经被全部被放于a中,直接将左半侧部分放入a
a[k] = aux[i++];
else if (less(aux[j], aux[i])){ // 右侧元素小于左侧元素时,将右侧元素放入
num += mid+1-i; //此时右侧的这个元素a[j]和[a[i],a[mid]]整个区间的元素都是逆序对
a[k] = aux[j++];
}else a[k] = aux[i++];
}
//System.out.println(Arrays.toString(a));
} public static void main(String[] args) {
Integer[] a = { 6,5,2,3,4,1 };
System.out.println(inversionsNum(a));
System.out.println(Arrays.toString(a));
}
}
Coursera Algorithms week3 归并排序 练习测验: Counting inversions的更多相关文章
- Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list
题目原文: Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items un ...
- Coursera Algorithms week3 归并排序 练习测验: Merging with smaller auxiliary array
题目原文: Suppose that the subarray a[0] to a[n-1] is sorted and the subarray a[n] to a[2*n-1] is sorted ...
- Coursera Algorithms week3 快速排序 练习测验: Selection in two sorted arrays(从两个有序数组中寻找第K大元素)
题目原文 Selection in two sorted arrays. Given two sorted arrays a[] and b[], of sizes n1 and n2, respec ...
- Coursera Algorithms week3 快速排序 练习测验: Decimal dominants(寻找出现次数大于n/10的元素)
题目原文: Decimal dominants. Given an array with n keys, design an algorithm to find all values that occ ...
- Coursera Algorithms week3 快速排序 练习测验: Nuts and bolts
题目原文: Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is t ...
- Coursera Algorithms week1 算法分析 练习测验: Egg drop 扔鸡蛋问题
题目原文: Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg ...
- Coursera Algorithms week1 算法分析 练习测验: 3Sum in quadratic time
题目要求: Design an algorithm for the 3-SUM problem that takes time proportional to n2 in the worst case ...
- Coursera Algorithms week2 基础排序 练习测验: Dutch national flag 荷兰国旗问题算法
第二周课程的Elementray Sorts部分练习测验Interview Questions的第3题荷兰国旗问题很有意思.题目的原文描述如下: Dutch national flag. Given ...
- Coursera Algorithms week4 基础标签表 练习测验:Inorder traversal with constant extra space
题目原文: Design an algorithm to perform an inorder traversal of a binary search tree using only a const ...
随机推荐
- C# 打开模态对话框 和打开文件夹
C# 打开另一个窗体,(模态对话框) Form1 frm= new Form1(); //创建对象 DialogResult retServer = frm.ShowDialog(); //模式对话框 ...
- Sprinboot优雅配置监听,并记录所有启动事件
在阅读Springboot启动源码的时候,发现Springboot自动启动listeners是通过uopeizhi文件配置的,本文就是采用Springboot方式自动装入listeners. 项目依赖 ...
- C# DataTable扩展方法
在日常搬砖中,总结了一些简单的扩展方法. public static bool IsNullOrEmpty(this DataTable dt) { ; } public static bool Is ...
- 使用Robo 3T 软件管理MongoDB数据库如何执行命令行shell
比如使用命令行的方式查看数据库runoobdb中的sites集合(数据表)中的所有数据 1.在连接名的地方鼠标右键选择“open shell” 2.在出现的shell窗口中输入一下命令行,然后按ctr ...
- python - 函数的定义和使用
目录 函数的定义和使用 一. 为什么要用函数? 二. 函数的参数 三. 函数的变量 global和nolocal 四. 递归函数 五. lamabda匿名函数 函数的定义和使用 1 def test( ...
- 洛谷 2387 NOI2014魔法森林 LCT
[题解] 我们先把边按照$a$值从小到大排序,并按照这个顺序加边. 如果当前要加入的边连接的两点$u$与$v$已经是连通的,那么直接加入这条边就会出现环.这时我们需要删除这个环中$b$值最大的边.因此 ...
- 解析特殊格式的xml到map
由于项目特殊,需要解析的xml文档样式特别,所以自己写了一个解析特殊xml的方法 先提供xml样式 <?xml version="1.0" encoding="UT ...
- windows 实现vue命令行
在代码编辑器里写好文件的位置,以及相关的命令,保存文件类型是.cmd
- 创建序列化器,序列化管理器,closureSerializer
创建序列化器,序列化管理器,closureSerializer //通过反射创建序列化对象 // Create an instance of the class with the given name ...
- HDU - 3556 - Continued Fraction
先上题目: Continued Fraction Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Jav ...