[LintCode] Nuts and Bolts
2015-11-11 16:18
375 查看
The question is actually a quick sort problem. The basic idea is:
1st, we pick a “nut” from nuts pile.
2nd we divide bolts into two parts according to the “nut”;
3rd we find the matching bolt
4th then we divide our nuts into two parts
5th using recursion to sort our bolts and nuts!
Done.
How to partition? it takes some time to figure it out…qwq
1st, we pick a “nut” from nuts pile.
2nd we divide bolts into two parts according to the “nut”;
3rd we find the matching bolt
4th then we divide our nuts into two parts
5th using recursion to sort our bolts and nuts!
Done.
How to partition? it takes some time to figure it out…qwq
/** * 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) { // write your code here if(nuts.empty() || bolts.empty()) return; int n = nuts.size(), m = bolts.size(); if(m!=n) return; quickSort(nuts,bolts,compare, 0, n-1); } void quickSort(vector<string>& nuts, vector<string>& bolts, Comparator compare, int start, int end){ if(start >= end) return; int idx = partition(nuts,bolts[start], compare, start, end); partition(bolts, nuts[idx], compare, start, end); quickSort(nuts, bolts, compare, start, idx-1); quickSort(nuts, bolts, compare, idx+1, end); } int partition(vector<string>& NorB, string pivot, Comparator compare, int start, int end){ int m = start;// m indicates the actual position of pivot. for(int i = start+1; i<=end; ++i){ if(compare.cmp(pivot, NorB[i]) == 1 || compare.cmp(NorB[i],pivot) == -1){ swap(NorB[++m],NorB[i]); }else if(compare.cmp(pivot,NorB[i]) == 0 || compare.cmp(NorB[i], pivot) == 0){ swap(NorB[start],NorB[i]); --i; } } swap(NorB[m], NorB[start]); return m; } };
相关文章推荐
- LintCode-最大数
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- 中位数 21% 通过 给定一个未排序的整数数组,找到其中位数。 中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数
- LintCode 翻转二叉树
- LintCode 寻找缺失的数
- Lintcode 二叉树的后序遍历
- Lintcode 二叉树中序遍历
- Lintcode 二叉树前序遍历
- Lintcode 尾部零的个数
- Lintcode 比较字符串
- Lintcode 主元素
- Lintcode解题笔记 - 岛屿的个数
- LintCode -合并两个排序链表
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- 20150708 lintcode 总结 Minimum Path Sum