leet_406_queue_reconstruction_by_height(按照身高和所给序列要求对序列重建)

  • leet:地址
  • 问题描述:
    • 有一打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 现需要按照该整数对(h,k)表示的要求 编写一个算法来重建这个队列以满足该要求。
  • 输入输出样例:
    • 输入: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
    • 输出:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
  • 解题思路:贪心算法
    • 先按身高(h)降序排序,相同身高按照k升序排序来重构队列。
    • 对重构出的序列按照插入排序的原则,将元素顺序地按照k值插入到结果队列中。
    • 形象解释:
      • 在这里插入图片描述
  • Python代码1:
def reconstruct(people):
    res, dic, height = [], {}, []
    for i in range(len(people)):
        p = people[i]
        if p[0] in dic:
            dic[p[0]].append((p[1], i))
        else:
            dic[p[0]] = [(p[1], i)]
            height.append(p[0])
    height.sort()
    for h in height[::-1]:
        dic[h].sort()
        for p in dic[h]:
            res.insert(p[0], people[p[1]])
            #res.insert(p[0], (h, p[0]))
    return res
  • Python代码2:
class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        people = sorted(people, key = lambda x: (-x[0], x[1]))
        res = []
        for p in people:
            res.insert(p[1], p)
        return res

主调函数

if __name__ == "__main__":
    #people_str = sys.argv[1] #[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
    people_str = "[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]"
    people = eval(people_str)
    print("result is :" + str(reconstruct(people)))
    print("ok")
  • c++ 代码
    • 代码重点:
      • 比较函数中使用回调函数
      • vector的insert函数的使用(有三种使用方式)。
class Solution
{
public:
	vector<pair<int, int>> reconstructQueue(vector<pair<int, int>> people)
	{
		auto comp = [](pair<int, int> a, pair<int, int> b)
		{return a.first > b.first || (a.first == b.first && a.second < b.second); };
		sort(people.begin(), people.end(), comp);
		vector<pair<int, int>> res;
		for (auto& p : people)
			res.insert(res.begin() + p.second, p);
		return res;
	}	
};

c++ 主调函数

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int main(int argc, char* argv[])
{
	vector<pair<int, int>> data = {make_pair(7,0), make_pair(4, 4), make_pair(7,1), make_pair(5, 0), make_pair(6, 1), make_pair(5, 2)};
	Solution solution;
	vector<pair<int, int>> res = solution.reconstructQueue(data);
	for (auto p : res)
	{
		cout << "(" << p.first << "," << p.second << ")" << endl;
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值