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 ...
随机推荐
- 开发者自建IM服务器必须要解决的几个问题!
有很多朋友的项目需要用到即时通讯,几年前鄙人的项目也是如此,当年没有选择,只能自建了IM服务器,几年下来跨了不少的坑,想想都甚是后怕.总结此文为后来还想自建IM的朋友提个醒,或许能找到更好的解决之路. ...
- MVC5+EasyUI+EF6+Linq通用权限系统出炉(1)
1.先晒一下结构吧,
- dubbo之延迟连接及粘滞链接接
延迟连接 延迟连接用于减少长连接数.当有调用发起时,再创建长连接.1 <dubbo:protocol name="dubbo" lazy="true" / ...
- kickstart配置文件详解和system-config-kickstart (转载)
kickstart是什么 许多系统管理员宁愿使用自动化的安装方法来安装红帽企业 Linux.为了满足这种需要,红帽创建了kickstart安装方法.使用kickstart,系统管理员可以 ...
- day11-函数对象、名称空间和作用域
目录 函数对象 函数的嵌套 名称空间和作用域 内置名称空间 全局名称空间 局部名称空间 作用域 全局作用域 局部作用域 global和nonlocal 函数对象 在Python中,一切皆对象,函数也是 ...
- Python3:numpy模块中的argsort()函数
Python3:numpy模块中的argsort()函数 argsort函数是Numpy模块中的函数: >>> import numpy >>> help(nu ...
- gitlab的添加密钥
1.在本地电脑下载git的客户端并且安装 2.鼠标右键左面选中Git Bash Here 3.操作如下图生成密钥 4.将密钥复制过来添加到gitLab中 5.Eclipse配置密钥 6.在git创建的 ...
- seleniumd对象的操作方法,属性,keys
这是通过find方法找到的页面元素,此对象提供了多种方法,让我们可以与页面元素进行交互,例如点击.清空. 目录: 1. 方法 2. 属性 3. keys 方法 clear()清空 如果当前元素中有文本 ...
- Boolean Expressions
Boolean Expressions Time Limit: 1000MS Memory Limit: 30000K Description The objective of the ...
- [bzoj3669][Noi2014]魔法森林_LCT_并查集
魔法森林 bzoj-3669 Noi-2014 题目大意:说不明白题意系列++……题目链接 注释:略. 想法:如果只有1个参量的话spfa.dij什么的都上来了. 两个参量的话我们考虑,想将所有的边按 ...