zoukankan      html  css  js  c++  java
  • sort学习 LeetCode #406 Queue Reconstruction by Height

    用python实现多级排序,可以像C语言那样写个my_cmp,然后在sort的时候赋给参数cmp即可

    但实际上,python处理cmp 是很慢的,因为每次比较都会调用my_cmp;而使用key和reverse就快得多,因为只需要在排序开始时处理一次即可,因此在排序的时候能不用cmp就尽量不用

    另外可以用operator函数中的itemgetter,和attrgetter实现基于key的(多级)排序:

    from operator import itemgetter, attrgetter
    sorted(people, key=itemgetter(0,1))
    sorted(people, key=attrgetter('h','k'))

    itemgetter通过属性的下标指定key,attrgetter通过属性名指定key

    趁热打铁,用sort实现一下 LeetCode #406 Queue Reconstruction by Height

    https://leetcode.com/problems/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]]

    基本思路很简单,对people进行排序,h越大k越小的排越前,然后按顺序先给个子高的排位置,再给个子矮的排

    因为个子高的位置排好后,再怎么对个子矮的排,都不会影响个子高的人的相对位置

    这里的排序涉及两个key,所以要用多级排序

    先用传统的cmp方法实现

    def reconstructQueue(self, people):
      def my_cmp(p1,p2):
            return cmp(p2[1],p1[1]) if p1[0]==p2[0] else cmp(p1[0],p2[0])
        
        people.sort(cmp = my_cmp,reverse = True)
        ans = []
        for peo in people:
            ans.insert(peo[1],peo)
        return ans

    耗时情况

    现在改用基于key实现多级排序,由于h是降序,k是升序,所以暂时还不知道怎么用itemgetter实现,只会自己写一个my_key =  =、

    由于sort不reverse,所以my_key中返回的是负的h(people[0])和正的k(people[1])来分别实现降序和升序

    def reconstructQueue(self, people):
        def my_key(people):
            return -people[0],people[1]
        
        people.sort(key=my_key)
        ans = []
        for peo in people:
            ans.insert(peo[1],peo)
        return ans

    耗时情况

    可以看出sort基于key时在速度上确实快于基于cmp

  • 相关阅读:
    MAC subline批处理
    Git 所有常用命令
    【React入门】React父子组件传值demo
    【fullGC】内存监控工具
    【dockerFile配置jvm 启动参数】dockerFile 参数解释
    【总结】程序人生,每天进步一点点,以及曾经的梦想
    【记录】Field required a single bean, but 2 were found:
    【maven 】jar包冲突-记一次冲突解决
    PAT甲题题解-1052. Linked List Sorting (25)-排序
    PAT甲题题解-1053. Path of Equal Weight (30)-dfs
  • 原文地址:https://www.cnblogs.com/liziran/p/6106534.html
Copyright © 2011-2022 走看看