题目原文:

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的更多相关文章

  1. Coursera Algorithms week3 快速排序 练习测验: Decimal dominants(寻找出现次数大于n/10的元素)

    题目原文: Decimal dominants. Given an array with n keys, design an algorithm to find all values that occ ...

  2. 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 ...

  3. Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list

    题目原文: Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items un ...

  4. 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 ...

  5. 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 ...

  6. Coursera Algorithms week1 算法分析 练习测验: Egg drop 扔鸡蛋问题

    题目原文: Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg ...

  7. 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 ...

  8. (转)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 ...

  9. Coursera Algorithms week2 基础排序 练习测验: Dutch national flag 荷兰国旗问题算法

    第二周课程的Elementray Sorts部分练习测验Interview Questions的第3题荷兰国旗问题很有意思.题目的原文描述如下: Dutch national flag. Given ...

随机推荐

  1. Java_Web三大框架之Hibernate+HQL语言基础

    12.1 HQL语言基础Hibernate查询语言为HQL(Hibernate Query Language),可以直接使用实体类名及属性.HQL语法类似于SQL,有SQL的关键词如select.fr ...

  2. day09-文件的操作

    目录 文件的基本操作 文件 什么是文件 如何使用文件 打开&关闭文件 打开&关闭文件 del f和f.close()的区别 文件路径 打开模式(不写默认是r) 编码格式 补充(open ...

  3. smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp

    报错信息 smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp7,DsmowAA3uguL7e1cyvkyFw--.22553S3 1559096715,ple ...

  4. 文件上传原理--FileReader

    单个文件:<div> <input value="上传" type="file" id="photos_upload"&g ...

  5. Spring处理自动装配的歧义性

    1.标识首选的bean 2.使用限定符@Qualifier 首先在bean的声明上添加@Qualifier 注解: @Component @Qualifier("cdtest") ...

  6. 04 学习java养成良好的写作习惯

    1, 驼峰命名法 首字母大写 2, 写的时候大小中括号都补全,不忘记分号 不要都放在一行上 3, 缩进对其,tab键 4, 严格要求自己,养成良好的写作风格 5, javadoc可以将文档注释,直接生 ...

  7. Oracle ASM注意事项

    ASM是负载均衡的存储策略,加新磁盘会将其它盘数据平均迁移到新磁盘,删除磁盘会将删除磁盘数据平均写回其它磁盘 1.同一磁盘组如果是在raid上,划分的磁盘越少越好,磁盘组分布在不同raid上性能好: ...

  8. 实验十二 团队作业8:软件测试与Alpha冲刺 第四天

    项目 内容 这个作业属于哪个课程 老师链接 这个作业的要求在哪里 实验十二 团队作业8:软件测试与Alpha冲刺 团队名称 Always Run! 作业学习目标 (1)掌握软件测试基础技术 (2)学习 ...

  9. ACdream 1032 Component

    Component Time Limit: 5000ms Memory Limit: 64000KB This problem will be judged on ACdream. Original ...

  10. 清北学堂模拟赛d7t1 消失的数字

    题目描述 现在,我的手上有 n 个数字,分别是 a1; a2; a3; :::; an.我现在需要删除其中的 k 个数字.当然我不希望随随便便删除,我希望删除 k个数字之后,剩下的 n - k 个数中 ...