[LintCode] Nuts and Bolts
来源:互联网 发布:怎么查淘宝授权的真伪 编辑:程序博客网 时间:2024/05/24 06:31
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
/** * 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; }};
0 0
- [LintCode] Nuts and Bolts
- lintcode(399)Nuts 和 Bolts 的问题
- uva 11138 - Nuts and Bolts(二分匹配)
- UVa11138 - Nuts and Bolts(二分匹配)
- R Programming: Part 1 - Nuts and Bolts
- Hardware Virtualization: the Nuts and Bolts / EPT / VPID
- Matching Nuts and Bolts 螺母螺帽的匹配
- 螺丝和螺帽Nuts and bolts 《算法》2.3.15
- 事务处理的nuts和bolts
- 《算法》第二章——Nuts and bolts(螺丝和螺帽)
- 题目:nuts 和 bolts 的问题
- 399.Nuts & Bolts Problem-Nuts 和 Bolts 的问题(中等题)
- Nuts
- Codeforces Round #332 (Div. 2) E. Sandy and Nuts
- Codeforces 599E Sandy and Nuts 状压DP
- Bolts介绍
- bolts-android
- Bolts-Android
- 多适配的小问题
- MySQL学习笔记2-System administration
- ScheduledExecutorService实现viewpager的自动切换
- MIME类型定义以及常用的类型
- Oracle Advanced Queue (DBMS_AQ/DMBS_AQADM)
- [LintCode] Nuts and Bolts
- C项目开发—通讯录(二) 初始化、查看、添加功能实现
- Spring、Spring自动扫描和管理Bean
- js+php实现comet(ajax长轮询)推送功能
- angular源码目录结构
- Scala排序简写及效率
- 使用Java和JS访问cookies
- IOS消息推送之APNS
- cruskal算法求最小支撑树 打印支撑树的边集合 带图例