LintCode 399 - Nuts & Bolts Problem


https://www.lintcode.com/problem/nuts-bolts-problem/description
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.
Using the function we give you, you are supposed to sort nuts or bolts, so that they can map in order.


Example

Given nuts = ['ab','bc','dd','gg'], bolts = ['AB','GG', 'DD', 'BC'].
Your code should find the matching of bolts and nuts.
According to the function, one of the possible return:
nuts = ['ab','bc','dd','gg'], bolts = ['AB','BC','DD','GG'].
If we give you another compare function, the possible return is the following:
nuts = ['ab','bc','dd','gg'], bolts = ['BC','AA','DD','GG'].
So you must use the compare function that we give to do the sorting.
The order of the nuts or bolts does not matter. You just need to find the matching bolt for each nut.
https://www.jianshu.com/p/f4f24c25d109
螺帽螺母问题脱胎于排序问题,这里的特别之处在于需要通过两个array进行对应的排序。这就需要利用一个array中的元素对另一个array进行partition,并反过来重复这一个过程,最终让两个array都满足comparator所定义的相同顺序。
这里要注意的是partition的变式,因为pivot并非来源当前array,只能通过一方元素作为基准,对另一个array进行partition。
核心在于:首先使用 nuts 中的某一个元素作为基准对 bolts 进行 partition 操作,随后将 bolts 中得到的基准元素作为基准对 nuts 进行 partition 操作。
https://algorithm.yuanbin.me/zh-hans/problem_misc/nuts_and_bolts_problem.html
首先结合例子读懂题意,本题为 nuts 和 bolts 的配对问题,但是需要根据题目所提供的比较函数,且 nuts 与 nuts 之间的元素无法直接比较,compare 仅能在 nuts 与 bolts 之间进行。首先我们考虑若没有比较函数的限制,那么我们可以分别对 nuts 和 bolts 进行排序,由于是一一配对,故排完序后即完成配对。那么在只能通过比较对方元素得知相对大小时怎么完成排序呢?
我们容易通过以一组元素作为参考进行遍历获得两两相等的元素,这样一来在最坏情况下时间复杂度为 O(n^2), 相当于冒泡排序。根据排序算法理论可知基于比较的排序算法最好的时间复杂度为 O(n \log n), 也就是说这道题应该是可以进一步优化。回忆一些基于比较的排序算法,能达到 O(n \log n) 时间复杂度的有堆排、归并排序和快速排序,由于这里只能通过比较得到相对大小的关系,故可以联想到快速排序。
快速排序的核心即为定基准,划分区间。由于这里只能以对方的元素作为基准,故一趟划分区间后仅能得到某一方基准元素排序后的位置,那通过引入 O(n) 的额外空间来对已处理的基准元素进行标记如何呢?这种方法实现起来较为困难,因为只能对一方的元素划分区间,而对方的元素无法划分区间进而导致递归无法正常进行。
山穷水尽疑无路,柳暗花明又一村。由于只能通过对方进行比较,故需要相互配合进行 partition 操作(这个点确实难以想到)。核心在于:首先使用 nuts 中的某一个元素作为基准对 bolts 进行 partition 操作,随后将 bolts 中得到的基准元素作为基准对 nuts 进行 partition 操作。
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
https://www.jiuzhang.com/solutions/nuts-bolts-problem/
nuts和bolts数组内的元素是一一对应的. 并且元素之间是有大小关系的.
题意可以这么理解: nuts是一个排列, bolts也是一个排列, 需要把它们变成同一个排列(不一定是升序排列或降序),
但是我们仅仅可以比较nuts的某个元素和bolts的某个元素.
我们同时将两个数组都排成升序以让它们满足按照顺序一一对应的关系.
排序的过程类似快速排序.
定义 quickSort(nuts, bolts, l, r, compare)为将两个数组的[l, r]区间排好序
  1. 选取比如nuts[l]作为pivot, 将bolts数组根据pivot做好划分(比它小的在左边, 比它大的在右边)
  2. 因为只能借助对方数组的元素进行比较, 所以此时借用bolts内的该值对nuts再进行一次划分
  3. 递归处理左右子区间
关键在于2, 如果没有这一步, 那么nuts不会变成有序的. 最终也无法按照顺序一一对应

 * 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.
*/
     * @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[l]
        int part_inx = partition(nuts, bolts[l], 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) {
        for (int i = l; i <= u; i++) {
            if (compare.cmp(str[i], pivot) == 0 || 
                compare.cmp(pivot, str[i]) == 0) {
                swap(str, i, l);
                break;
            }
        }
        String now = str[l];
        int left = l; 
        int right = u;
        while (left < right) {
            while (left < right && 
            (compare.cmp(str[right], pivot) == 1 || 
            compare.cmp(pivot, str[right]) == -1)) {
                right--;
            }
            str[left] = str[right];
            
            while (left < right && 
            (compare.cmp(str[left], pivot) == -1 || 
            compare.cmp(pivot, str[left]) == 1)) {
                left++;
            }
            str[right] = str[left];
        }
        str[left] = now;

        return left;
    }
    https://www.cnblogs.com/evasean/p/7236234.html
    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,满足题目要求
     13     Map<Nut, Bolt> pairs = new HashMap<Nut, Bolt>(); // 存储配对的螺帽和螺丝对
     14     Nut[] nuts;
     15     Bolt[] bolts;
     16     int n;
     17 
     18     public NutsAndBolts(Nut[] nuts, Bolt[] bolts, int n) {
     19         this.nuts = nuts;
     20         this.bolts = bolts;
     21         this.n = n;
     22     }
     23 
     24     private int compare(NBParent v, NBParent w) {
     25         int vsize = v.getSize();
     26         int wsize = w.getSize();
     27         if (vsize == wsize) return 0;
     28         else if (vsize > wsize) return 1;
     29         else return -1;
     30     }
     31     private void exch(NBParent[] nb, int i, int j){
     32         NBParent t = nb[i];
     33         nb[i]=nb[j];
     34         nb[j]=t;
     35     }
     36     
     37     public Map<Nut, Bolt> findPairs() {
     38         sort(bolts,0,n-1); //先对bolts进行快速排序
     39         for(int i = 0; i<n;i++){ //遍历nuts,并在bolts中寻找其成对的bolt
     40             Nut nut = nuts[i];
     41             Bolt bolt= findBolt(nut); 
     42             if(bolt != null)
     43                 pairs.put(nut, bolt);
     44         }
     45         return pairs;
     46     }
     47     private Bolt findBolt(Nut nut){ //在排好序的bolts中二分查找nut
     48         int lo = 0; 
     49         int hi = n-1;
     50         while(lo<=hi){
     51             int mid = lo+(hi-lo)/2;
     52             int cr = compare(bolts[mid],nut);
     53             if(cr<0) lo = mid+1;
     54             else if(cr>0) hi = mid-1;
     55             else return bolts[mid];
     56         }
     57         return null;
     58     }
     59     private void sort(NBParent[] nb, int lo, int hi){
     60         if(hi<=lo) return;
     61         int j = partition(nb,lo,hi);
     62         sort(nb,lo,j-1);
     63         sort(nb,j+1,hi);
     64     }
     65     
     66     private int partition(NBParent[] nb, int lo, int hi){
     67         int i = lo;
     68         int j = hi+1;
     69         NBParent v = nb[lo];
     70         while(true){
     71             while(compare(nb[++i],v)<0) if(i==hi) break;
     72             while(compare(nb[--j],v)>0) if(j==lo) break;
     73             if(i>=j) break;
     74             exch(nb,i,j);
     75         }
     76         exch(nb,lo,j);
     77         return j;
     78     }
    


    Labels

    LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

    Popular Posts