406. Queue Reconstruction by Height
来源:互联网 发布:JS域名代码授权源码 编辑:程序博客网 时间:2024/05/29 03:51
Description
height of the person and k
is the number of people in front of this person who have a height greater than or equal to h
. Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
Input:[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]Output:[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
简要题解:
这道题总的解题方向是采用贪心算法。具体做法是不断循坏people向量的各个元素直到该向量为空。每次从people中取出一个,在result中找到一个刚好可以放的位置放入。如果找不到可以放的位置放就跳过这个元素,等待下一轮循坏再继续找位置。
但是这样做会有点问题,我们必须保证后放入result的元素不会影响到先放入result的元素。因此,需要对people中的每个人按身高大小由高到底排序。(身高较低的不管怎么放都不会影响到身高较高的人)。还要注意到,对于两个身高相同的情况,k值小的应该放在前面。因为,身高相同的两个人,在result中k值小的一定是放在k值较大的那个人的前面。也就是说,在身高相同的情况下,k值较小的可能会影响k值较大的那个人。排完序后,就采用前面说的那种贪心算法来构造result就可得到正确的结果。
代码:
class Solution {public: static vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) { vector<pair<int, int> > result; for (int i = 0; i < people.size(); i++) for (int j = i + 1; j < people.size(); j++) if ((people[i].first < people[j].first) || (people[i].first == people[j].first && people[i].second > people[j].second)) { pair<int, int> temp = people[i]; people[i] = people[j]; people[j] = temp; } while (!people.empty()) { vector<pair<int, int> >::iterator iter1, iter2; for (iter1 = people.begin(); iter1 != people.end(); iter1++) { int count = 0; int flag = false; for (iter2 = result.begin(); iter2 != result.end(); iter2++) { if (count == iter1->second + 1) { iter2--; result.insert(iter2, *iter1); people.erase(iter1); flag = true; break; } if (iter2->first >= iter1->first) count++; } if (!flag && count == iter1->second + 1) { pair<int, int> temp = result[result.size()-1]; result[result.size()-1] = *iter1; result.push_back(temp); people.erase(iter1); flag = true; } if (!flag && count == iter1->second) { result.push_back(*iter1); people.erase(iter1); flag = true; } if (flag) break; } } return result; }};
阅读全文
0 0
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 初入研究生
- vijos1456 最小总代价
- gentconf命令解释及用法
- Expression Expand
- Git 分布式版本控制系统 基本命令行操作
- 406. Queue Reconstruction by Height
- 凉风起天末
- Lucas定理的应用
- JS正则表达式二
- 注意:你LR的HTTP长连接可能是假的
- python3 数据类型之 列表、字典、元组
- weex学习之路(二)---组件封装(1)
- 欢迎使用CSDN-markdown编辑器
- UltraViewPager 无法显示多屏问题