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 to find the corresponding pairs of nuts and bolts. Each nut fits exactly one bolt and each bolt fits exactly one nut. By fitting a nut and a bolt together, the carpenter can see which one is bigger (but the carpenter cannot compare two nuts or two bolts directly). Design an algorithm for the problem that uses nlogn compares (probabilistically).
分析:
题意是有一堆螺帽和螺钉,分别为n个,每个螺帽只可能和一个螺钉配对,目标是找出配对的螺帽和螺钉。螺帽和螺钉的是否配对只能通过螺帽和螺钉比较,不能通过两个螺帽或两个螺钉的比较来判断。比较次数要求限制在nlogn次
设计过程中思考了如下几个问题:
1. 螺帽和螺钉的配对怎么判断?
-螺帽和螺钉分别设计成不同的对象,每个对象都有个size属性,通过判断不同对象的size是否相等来判断是否配对
2. 为什么不能通过把螺帽和螺钉分别排序,然后对应位置一一配对的方式进行设计?
-假如那堆螺帽和螺钉中分别有落单的不能配对的,这种排序后靠位置来匹配的配对方式就明显不合适了,也就是说这种做法鲁棒性太差
3. 既然不能分别排序,那采用把螺帽和螺钉混在一起排序的方式如何?
-恩,貌似可行,但遇到螺帽和螺钉中分别有落单的不能配对的情况,我怎么判断某个位置i处元素是与i-1处的元素配对?还是与i+1处的元素配对?还是i处元素落单呢?
综上几个问题考虑之后,决定如下设计:
a. 现将螺帽进行快速排序,复杂度nlogn
b. 逐个遍历螺钉组中的每个螺钉,在已排序的螺帽中,采用二分查找的方法查找其配对的螺帽。比较次数nlogn,满足题目要求
代码如下
package week3;
/**
* 螺帽和螺钉共有父类
* @author evasean www.cnblogs.com/evasean/
*/
public class NBParent {
public NBParent(int size){
this.size = size;
}
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
package week3;
/**
* 螺帽类
* @author evasean www.cnblogs.com/evasean/
*/
public class Nut extends NBParent{
public Nut(int size){
super(size);
}
}
package week3;
/**
* 螺钉类
* @author evasean www.cnblogs.com/evasean/
*/
public class Bolt extends NBParent{
public Bolt(int size){
super(size);
}
}
package week3; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import edu.princeton.cs.algs4.StdRandom;
/**
* 螺帽类
* @author evasean www.cnblogs.com/evasean/
*/
public class NutsAndBolts {
Map<Nut, Bolt> pairs = new HashMap<Nut, Bolt>(); // 存储配对的螺帽和螺丝对
Nut[] nuts;
Bolt[] bolts;
int n; public NutsAndBolts(Nut[] nuts, Bolt[] bolts, int n) {
this.nuts = nuts;
this.bolts = bolts;
this.n = n;
} private int compare(NBParent v, NBParent w) {
int vsize = v.getSize();
int wsize = w.getSize();
if (vsize == wsize) return 0;
else if (vsize > wsize) return 1;
else return -1;
}
private void exch(NBParent[] nb, int i, int j){
NBParent t = nb[i];
nb[i]=nb[j];
nb[j]=t;
} public Map<Nut, Bolt> findPairs() {
sort(bolts,0,n-1); //先对bolts进行快速排序
for(int i = 0; i<n;i++){ //遍历nuts,并在bolts中寻找其成对的bolt
Nut nut = nuts[i];
Bolt bolt= findBolt(nut);
if(bolt != null)
pairs.put(nut, bolt);
}
return pairs;
}
private Bolt findBolt(Nut nut){ //在排好序的bolts中二分查找nut
int lo = 0;
int hi = n-1;
while(lo<=hi){
int mid = lo+(hi-lo)/2;
int cr = compare(bolts[mid],nut);
if(cr<0) lo = mid+1;
else if(cr>0) hi = mid-1;
else return bolts[mid];
}
return null;
}
private void sort(NBParent[] nb, int lo, int hi){
if(hi<=lo) return;
int j = partition(nb,lo,hi);
sort(nb,lo,j-1);
sort(nb,j+1,hi);
} private int partition(NBParent[] nb, int lo, int hi){
int i = lo;
int j = hi+1;
NBParent v = nb[lo];
while(true){
while(compare(nb[++i],v)<0) if(i==hi) break;
while(compare(nb[--j],v)>0) if(j==lo) break;
if(i>=j) break;
exch(nb,i,j);
}
exch(nb,lo,j);
return j;
} public static void main(String[] args) {
int n = 10;
Nut[] nuts = new Nut[n];
Bolt[] bolts = new Bolt[n];
for (int i = 0; i < n-1; i++) {
Nut nut = new Nut(i + 1);
nuts[i] = nut;
Bolt bolt = new Bolt(i + 2);
bolts[i] = bolt;
}
//故意做一对不一样的
nuts[n-1] = new Nut(13);//nuts的size分别为{1,2,3,4,5,6,7,8,9,13}
bolts[n-1] = new Bolt(1);//bolts的size分别是{2,3,4,5,6,7,8,9,10,1}
StdRandom.shuffle(nuts);
StdRandom.shuffle(bolts);
NutsAndBolts nb = new NutsAndBolts(nuts, bolts, n);
Map<Nut, Bolt> pairs = nb.findPairs();
Iterator<Entry<Nut, Bolt>> iter = pairs.entrySet().iterator();
while(iter.hasNext()){
Entry<Nut, Bolt> e = iter.next();
Nut nut = e.getKey();
Bolt bolt = e.getValue();
System.out.print("<"+nut.getSize()+","+bolt.getSize()+">,");
}
System.out.println();
}
}
Coursera Algorithms week3 快速排序 练习测验: Nuts and bolts的更多相关文章
- 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 快速排序 练习测验: 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 归并排序 练习测验: Shuffling a linked list
题目原文: Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items un ...
- 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 ...
- 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 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 ...
- (转)Nuts and Bolts of Applying Deep Learning
Kevin Zakka's Blog About Nuts and Bolts of Applying Deep Learning Sep 26, 2016 This weekend was very ...
- Coursera Algorithms week2 基础排序 练习测验: Dutch national flag 荷兰国旗问题算法
第二周课程的Elementray Sorts部分练习测验Interview Questions的第3题荷兰国旗问题很有意思.题目的原文描述如下: Dutch national flag. Given ...
随机推荐
- Linux 配置JDK + MyEclipse
版本:Ubuntu16.04: jdK: Java SE Development Kit 8u102; My Eclipse: 10.6; JDK配置的细致步骤参见此处. 就一点要注意: 请使用代码进 ...
- Appium 使用android_uiautomator定位元素时报错: The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource
使用 android_uiautomator 定位元素时(现在用的还不太熟,对于这个方法还需要加深了解)报错: 报错信息:The requested resource could not be fou ...
- Vue项目在IE浏览器报错polyfill-eventsource added missing EventSource to window
已经安装了babel-polyfill,依然报错.
- CAD绘制一个箭头(com接口)
1 2 3 4 5 6 7 8 //绘制一个箭头 axMxDrawX1.PathMoveToEx(1000, 300, 10, 10, 0); //设置路径下一点 axMxDrawX1.Path ...
- 00 python基础知识
''' ''' print('hello world!') ''' 变量 ''' # 变量的:‘tank’,会在内存中产生一份内存地址 #变量名:相当于一个门牌号,用于与变量进行绑定 # = :用来把 ...
- css的基础知识1
总结:css引用:1内联:在标签中加style属性,<标签名 style="样式1:样式值1:样式2:样式值2"> </标签名>.2.内嵌:在head标签中 ...
- Xpath语法与lxml库
1. Xpath 1 )什么是XPath? xpath(XML Path Language)是一门在XML和HTML文档中查找信息的语言,可用来在XML和HTML文档中对元素和属性进行遍历. 2) X ...
- python 列出出当前目录及所有子目录下的文件
[root@web1 test]# cat walk.py #!/usr/bin/python # -*- coding: UTF-8 -*- import os for root, dirs, fi ...
- BZOJ 1617 Usaco 2008 Mar. River Crossing渡河问题
[题解] 显然是个DP题. 设$f[i]$表示送$i$头牛过河所需的最短时间,预处理出$t[i]$表示一次性送i头牛过河所需时间,那么我们可以得到转移方程:$f[i]=min(f[i],f[i-j]+ ...
- sql 区分大小写查询
sql 区分大小写查询 select * FROM [Users] where userName collate Chinese_PRC_CS_AS='ADMIN'