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 ...
随机推荐
- mongodb分片集群安装教程
mongodb 集群包含副本集群,主从集群以及分片集群,分片集群比较复杂,这里测试我采用了三台机器,交差部署 blog地址:http://www.cnblogs.com/caoguo 一 .环境:#m ...
- 【js】数组置空的其他方式及使用场景
数组在js中属于引用型类型. var arr = [1, 2, 3]; a = []; 通常使用以上方式.如果使用场景必须使用方法置空, 可以采用arr.length = 0; 或者使用a.splic ...
- docker安装kong和kong-dashboard
1:docker安装遵循官方手册 2:安装kong 参考文档:https://getkong.org/install/docker/ 安装过程基本和文档一致,文档十分简单清晰. 但应注意,为了最新版k ...
- 优化yum下载安装慢,不断换mirror
不停地换mirror,为了解决这个问题,在网上搜了好多资料,总结出一个基于aliyun的mirror源 先检查:是否能正常上网,DNS是否正常,网关gw是否正常,若通过ping 不正常,则解决好网络, ...
- 【模板】最小生成树Kruskal
洛谷3366 #include<cstdio> #include<algorithm> using namespace std; ,maxm=; ,ans=; struct e ...
- Tkinter图形界面设计(GUI)
[因为这是我第一个接触的GUI图形界面python库,现在也不用了,所以大多数内容都来自之前花 钱买的一些快速入门的内容,可以当作简单的知识点查询使用] 在此声明:内容来自微信公众号GitChat,付 ...
- mybatis源码阅读-MappedStatement各个属性解析过程(八)
调用方 类org.apache.ibatis.builder.xml.XMLMapperBuilder private void configurationElement(XNode context) ...
- 清北学堂模拟赛d3t5 c
分析:其实就是一道数学题.如果以左下角的点为原点建立平面直角坐标系,那么点(b,a)是最容易卡住棺材的.我们求出棺材左边到点(b,a)的距离最小值,只有w小于等于这个最小值才能被拉过去.那么先求出左面 ...
- IDFTP连不上FTP服务器的解决方法
使用IDFTP连不上FTP服务端. 原来是IDFTP有2种模式:主动模式和被动模式. IDFTP默认是使用主动模式,如果FTP服务端设置使用被动模式,使用IDFTP连不上FTP服务端的. 解决方法: ...
- Python开发工具安装
v阅读目录 v写在前面 v基本概念 vWindows搭建python开发环境 v从Hello World开始 v博客总结 v博客前言 从大学开始玩python到现在参加工作,已经有5年了,现在的公司是 ...