Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with nut to see which one is bigger/smaller.

We will give you a compare function to compare nut with bolt.

Quick Sort Way: We can use quick sort technique to solve this. We represent nuts and bolts in character array for understanding the logic.

Nuts represented as array of character
char nuts[] = {‘@’, ‘#’, ‘$’, ‘%’, ‘^’, ‘&’}

Bolts represented as array of character
char bolts[] = {‘$’, ‘%’, ‘&’, ‘^’, ‘@’, ‘#’}

This algorithm first performs a partition by picking last element of bolts array as pivot, rearrange the array of nuts and returns the partition index ‘i’ such that all nuts smaller than nuts[i] are on the left side and all nuts greater than nuts[i] are on the right side. Next using the nuts[i] we can partition the array of bolts. Partitioning operations can easily be implemented in O(n). This operation also makes nuts and bolts array nicely partitioned. Now we apply this partitioning recursively on the left and right sub-array of nuts and bolts.

As we apply partitioning on nuts and bolts both so the total time complexity will be Θ(2*nlogn) = Θ(nlogn) on average.

Partition function类似sort colors

 /**
* public class NBCompare {
* public int cmp(String a, String b);
* }
* You can use compare.cmp(a, b) to compare nuts "a" and bolts "b",
* if "a" is bigger than "b", it will return 1, else if they are equal,
* it will return 0, else if "a" is smaller than "b", it will return -1.
* When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid.
*/
public class Solution {
/**
* @param nuts: an array of integers
* @param bolts: an array of integers
* @param compare: a instance of Comparator
* @return: nothing
*/
public void sortNutsAndBolts(String[] nuts, String[] bolts, NBComparator compare) {
if (nuts == null || bolts == null) return;
if (nuts.length != bolts.length) return; qsort(nuts, bolts, compare, 0, nuts.length - 1);
} private void qsort(String[] nuts, String[] bolts, NBComparator compare,
int l, int u) {
if (l >= u) return;
// find the partition index for nuts with bolts[u]
int part_inx = partition(nuts, bolts[u], compare, l, u);
// partition bolts with nuts[part_inx]
partition(bolts, nuts[part_inx], compare, l, u);
// qsort recursively
qsort(nuts, bolts, compare, l, part_inx - 1);
qsort(nuts, bolts, compare, part_inx + 1, u);
} private int partition(String[] str, String pivot, NBComparator compare,
int l, int u) { int low = l;
int high = u;
int i = low;
while (i <= high) {
if (compare.cmp(str[i], pivot) == -1 ||
compare.cmp(pivot, str[i]) == 1) {
swap(str, i, low);
i++;
low++;
}
else if (compare.cmp(str[i], pivot) == 1 ||
compare.cmp(pivot, str[i]) == -1) {
swap(str, i, high);
high--;
}
else i++;
}
return low;
} private void swap(String[] str, int l, int r) {
String temp = str[l];
str[l] = str[r];
str[r] = temp;
}
}

Lintcode: Nuts & Bolts Problem的更多相关文章

  1. [LintCode] Nuts & Bolts Problem 螺栓螺母问题

    Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping ...

  2. Lintcode399 Nuts & Bolts Problem solution 题解

    [题目描述] Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one m ...

  3. Nuts & Bolts Problem

    Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping ...

  4. LintCode A + B Problem

    原题链接在这里:http://www.lintcode.com/en/problem/a-b-problem/ 不让用 数学运算符,就用位运算符. a的对应位 ^ b的对应位 ^ carry 就是re ...

  5. LintCode "Post Office Problem" !!!

    * Non-intuitive state design class Solution { public: /** * @param A an integer array * @param k an ...

  6. [LintCode]——目录

    Yet Another Source Code for LintCode Current Status : 232AC / 289ALL in Language C++, Up to date (20 ...

  7. lintcode算法周竞赛

    ------------------------------------------------------------第七周:Follow up question 1,寻找峰值 寻找峰值 描述 笔记 ...

  8. 7九章算法强化班全解--------Hadoop跃爷Spark

    ------------------------------------------------------------第七周:Follow up question 1,寻找峰值 寻找峰值 描述 笔记 ...

  9. (C#)算法题

    1. Convert string from "AAABBCC" to "A3B2C2". 当面试者提出这个问题的时候,首先需要确认题意:譬如:字符串是不是顺序 ...

随机推荐

  1. windows应用程序框架及实例

    应用程序框架:同一类型应用程序的结构大致相同,并有很多相同的源代码,因此可以通过一个应用程序框架AFX(Application FrameWorks)编写同一类型应用程序的通用源代码. 主要向导: D ...

  2. oracle直接读写ms sqlserver数据库(一)如何下载oracle database gateway for sqlserver

    想从Oracle实时同步数据到Ms Sqlserver,需要在Oracle里面直连Sqlserver进行数据的读写,可以在Oracle服务器上安装oracle database gateway for ...

  3. C_输入一个整数N,输出从0~N(算法思考)

    1.for循环实现 #include <stdio.h> #include <time.h> clock_t start, stop; double duration; voi ...

  4. 11_ for 练习 _ Math.sqrt

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  5. [LeetCode] Swap Adjacent in LR String 交换LR字符串中的相邻项

    In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of ...

  6. PermissionDispatcher 运行时权限框架

    第一步在app的build.gradle文件中添加: dependencies { // PermissionDispatcher 框架的使用 implementation 'com.github.h ...

  7. 配置ssh框架启动tomcat服务器报异常Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

    在Spring中配置jdbc时,引用的是dbcp.jar包,在db.properties配置文件中,使用了之前的properties配置文件的用户名username(MySql用户名) 然后在启动服务 ...

  8. oc与c语言的相互调用

    一:OC调用C语言 C语言的.h文件 // // TestPrint.h // TestDemo // // Created by Techsun on 14-8-12. // Copyright ( ...

  9. Lucene.net 的性能探究--Lucene.net 的并发处理能力到底有多强?

    这篇博客并不是证明Lucene.net的性能有多强悍,实际上Lucene.net的并发能力并不让人很满意,这得看你怎么用它. 因为Lucene 本身就是一个搜索引擎的基础框架,相当于一辆车子的发动机, ...

  10. JS数组reduce()方法详解及高级技巧

    1.语法 arr.reduce(callback,[initialValue]) reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(或者上 ...