国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

LeetCode OJ 406. Queue Reconstruction by Height

2019-11-06 06:03:40
字體:
供稿:網(wǎng)友

LeetCode OJ 406. Queue Reconstruction by Height


Description

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the 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]]

解題思路

這個題目的解題方法一開始比較難想到。但是有了想法做起來就很簡單。 隊列中的元素(h,k)表示在這個元素前比h大的元素有k個。題意是要把這樣的元素組成的隊列排序。首先把元素排序:按照h的降序排列,h相等時,按照k的升序排列。然后我們再一個個把元素插入到結(jié)果隊列中。插入的方法是:插入到當(dāng)前隊列下標(biāo)為k的位置。因為我們之前插入的都是比這個元素的h值大的元素,因此當(dāng)前元素的h值就是隊列中所剩下未插入結(jié)果隊列的h值最大的元素了。而且k值是升序排列的,保證了結(jié)果插入的過程中不會越界。 eg. 題目中所給的輸入進行排序后 Input: [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]] 結(jié)果Result首先插入第一個元素[7,0]: Result: [[7,0]] 插入第二個元素[7,1],在Result中下標(biāo)為1的位置,即偏移量為1: Result: [[7,0], [7,1]] 插入第三個元素[6,1]: Result: [[7,0], [6,1], [7,1]] 插入第四個元素[5,0]: Result: [[5,0], [7,0], [6,1], [7,1]] 插入第五個元素[5,2]: Result: [[5,0], [7,0], [5,2], [6,1], [7,1]] 插入第六個元素[4,4]: Result: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

Note:

std::sort函數(shù)是全局的,如果第三個參數(shù)cmp不是靜態(tài)成員函數(shù)或者全局函數(shù),運行都會報錯。非靜態(tài)函數(shù)是依賴于具體對象的,因此調(diào)用sort函數(shù)時,只能調(diào)用不依賴于對象的靜態(tài)函數(shù)cmp。

代碼

個人github代碼鏈接

class Solution {public: static bool cmp(pair<int, int> p1, pair<int, int> p2){ return (p1.first > p2.first) || ((p1.first == p2.first) && (p1.second < p2.second)); } vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { vector<pair<int, int>> ans; sort(people.begin(), people.end(), cmp); for(auto p:people){ ans.insert(ans.begin() + p.second, p); } return ans; }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 大连市| 彩票| 威远县| 昌黎县| 蚌埠市| 彩票| 托克逊县| 慈溪市| 新竹市| 运城市| 镇巴县| 星座| 壶关县| 湖北省| 白水县| 长海县| 棋牌| 子长县| 遂平县| 海盐县| 吉木萨尔县| 阳城县| 镇原县| 江津市| 平安县| 济阳县| 阿瓦提县| 靖宇县| 马关县| 且末县| 翼城县| 宁国市| 德兴市| 白玉县| 宁明县| 遵义县| 鞍山市| 繁峙县| 龙山县| 炉霍县| 玛曲县|