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 ...
随机推荐
- [Windows Server 2012] IIS自带FTP配置方法
★ 欢迎来到[护卫神·V课堂],网站地址:http://v.huweishen.com★ 护卫神·V课堂 是护卫神旗下专业提供服务器教学视频的网站,每周更新视频.★ 本节我们将带领大家:IIS自带FT ...
- 实例分割:MaskXRCnn 与Visual Genome数据集
一.VG数据集 机器学习领域的突破突然让计算机获得了以未曾有的高精度识别图像中物体的能力--几乎达到了让人惊恐的程度.现在的问题是机器是否还能更上层楼,学会理解这些图片中所发生的事件. Visual ...
- 【转载】HTTP 基础与变迁
原文地址:https://segmentfault.com/a/1190000006689489 HTTP HTTP(HyperTextTransferProtocol)是超文本传输协议的缩写,它用于 ...
- Python基础——列表、元组操作
列表.元组操作 列表: 列表是Python中最基本的数据结构,列表是最常用的Python数据类型,列表的数据项不需要具有相同的类型.列表中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0 ...
- iOS crash log 解析 symbol address = stack address - slide 运行时获取slide的api 利用dwarfdump从dsym文件中得到symbol
概述: 为什么 crash log 内 Exception Backtrace 部分的地址(stack address)不能从 dsym 文件中查出对应的代码? 因为 ASLR(Address spa ...
- Jenkins里jobs和workspace什么区别
https://segmentfault.com/q/1010000012575095/a-1020000012590560 简单的说,job 中保存的是项目是在 jenkins 上的配置.日志.构建 ...
- accmcolor
accmcolor c; c.setcolorindex(1); playertablerecord.setcolor(c);
- C解析config
#cat bb.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include < ...
- js 随机数范围
Math.floor(Math.random()*(high-low+1) +low)
- JavaScript初步学习----基本使用,简单事件,修改样式,数据类型
JavaScript基本使用 JavaScript原名叫livescript,是一门动态类型,弱类型基于原型的脚本语言 用于页面特效,前后交替,后台开发(node) JavaScript写在s ...