LeetCode-Queue_Reconstruction_by_Height

題目:

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爲排在這個人之前高度比他高或和他一樣高的人的數量。寫下一個算法來重構這個隊列。

注意:

人的數量少於1,100。

例子

輸入:

[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

輸出:

[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

 

思路:

首先將這個數組排序:按數字對中的第一個數字從大到小排序,若兩個數字相等,再按後面的數字從小到大排序。排序好後再依次按後面的數字將數字對插入到對應的位置。

 

C++代碼(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

/*
bool cmp(const pair<int, int> a, const pair<int, int> b) {
	return a.first == b.first ? a.second<b.second : a.first>b.first;
}*/

class Solution {
public:
	vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
		if (people.size() == 0) return {};
		
		//sort(people.begin(), people.end(), cmp);   //若在外部定義cmp,則需要寫到class外面,若寫在class裏面,編譯不通過
		
		sort(people.begin(), people.end(), [](const pair<int, int> &a, const pair<int, int> &b) {  //上述sort的另一寫法
			return a.first == b.first ? a.second<b.second : a.first>b.first;});
		vector<pair<int, int>> ans;
		for (auto val : people)
			ans.insert(ans.begin() + val.second, val);
		return ans;
	}

};

int main()
{
	Solution s;
	vector<pair<int, int>> people = { {7,0},{4,4},{7,1},{5,0},{6,1},{5,2} };
	vector<pair<int, int>> res = s.reconstructQueue(people);
	for (auto m : res) {
		cout << m.first << "***" << m.second << " ";
	}
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章