leetcode_406. Queue Reconstruction by Height 按身高h和比他高的人的个数k的二元组(h,k) 排队

来源:互联网 发布:计算机的算法是 编辑:程序博客网 时间:2024/04/29 05:55

题目:

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高的人的个数。请将这些二元组进行排序。


代码:

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        
        n = len(people)
        if n < 2 :
            return people
        else :
            res = []    #存储排序后需要返回的结果
            height = []     #存储身高,对应new_people 的键的列表
            new_people = {}    #定义字典,键:身高    值:拥有该身高的k值,以及这个人对应的在people中的下标
            
            for i in xrange(n) :
                if people[i][0] not in new_people :    #如果这个身高之前没有作为键
                    new_people[people[i][0]] = [(people[i][1], i)]          #将身高作为键,将(k,i)作为值,存入字典中
                    height += [people[i][0]]          #存储第i个人的高度
                else :
                    new_people[people[i][0]] += [(people[i][1], i)]    #如果身高people[i][0]已在字典中存在,则将这个人的(k,i)插在后面,此时,键people[i][0]对应的值是一个列表,列表每个元素又是一个二元列表(k,i)。
            
            height.sort()          #按身高从低到高排序
            
            for x in height[::-1] :   #按身高从高到低存入res
                new_people[x].sort()         #对拥有同一身高的人,对他的k值进行排序,按从小到大的顺序
                for i in range(len(new_people[x])) :
                    res.insert(new_people[x][i][0],people[new_people[x][i][1]])   #从前往后将new_people[x]中的每个人按其k值,插入到res的第k个位置
            
            return res


笔记:

代码总体思路是:

1、对身高从高到第排序

2、在1的基础上,如果身高相同,则按k值从低到高排序

3、在1,2排好序的基础上,按顺序将元素按照其对应的k值插入结果列表的第k个位置(也不知道为啥)

代码参考:http://blog.csdn.net/sscssz/article/details/53099194


0 0
原创粉丝点击