当前位置: 首页 > 工具软件 > Bolts > 使用案例 >

Nuts & Bolts Problem

巫健柏
2023-12-01

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.

Example

Given nuts = ['ab','bc','dd','gg'], bolts = ['AB','GG', 'DD', 'BC'].

Your code should find the matching bolts and nuts.

one of the possible return:

nuts = ['ab','bc','dd','gg'], bolts = ['AB','BC','DD','GG'].

we will tell you the match compare function. 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.

Solution:

/**
 * class Comparator {
 *     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.
*/
class Solution {
public:
    /**
     * @param nuts: a vector of integers
     * @param bolts: a vector of integers
     * @param compare: a instance of Comparator
     * @return: nothing
     */
    void sortNutsAndBolts(vector<string> &nuts, vector<string> &bolts, Comparator compare) {
        auto sz = (int)nuts.size();
        if (sz == 0) return;
        qsort(nuts, bolts, compare, 0, sz-1);
    }
    
private:
    void qsort(vector<string>& nuts, vector<string>& bolts, Comparator c, int start, int end) {
        if (start >= end) return;
        auto m = help(nuts, bolts[start] , c, start, end);
        help(bolts, nuts[m], c, start, end);
        qsort(nuts, bolts, c, start, m-1);
        qsort(nuts, bolts, c, m+1, end);
    }

    int help(vector<string>& vec, const string& key, Comparator c, int start, int end) {
        int l = start;
        int r = end;
        int i = l;
        for (; i <= r; ++i) {
            if (c.cmp(vec[i], key) == 0 || c.cmp(key, vec[i]) == 0)
                break;
        }
        swap(vec[i], vec[l]);
        auto tmp = vec[l];
        while (l < r) {
            while (l < r && (c.cmp(vec[r], key) == 1 || c.cmp(key, vec[r]) == -1))
                --r;
            vec[l] = vec[r];
            while (l < r && (c.cmp(vec[l], key) == -1 || c.cmp(key, vec[l]) == 1))
                ++l;
            vec[r] = vec[l];
        }
        vec[l] = tmp;
        return l;
    }
};

转载于:https://www.cnblogs.com/deofly/p/nuts-bolts-problem.html

相关阅读

相关文章

相关问答