码迷,mamicode.com
首页 > 其他好文 > 详细

1051. Height Checker

时间:2020-06-29 15:25:43      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:diff   int   col   dex   bsp   排序   ini   htc   hot   

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.

Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.

这题的差评率非常高,因为描述和题目本身的意思严重不符合,他的本意是求有多少个人不在对应的位置上,而不是题目描述中所谓的最少需要移动多少个学生使得身高不递减。

比如[1,2,4,3]这个case,答案是2.所以根本不是题目描述的那样,否则答案是1,3和4掉换就完事了

这题本质是求有多少学生位置和排序后是不一致的

  • 1 <= heights.length <= 100
  • 1 <= heights[i] <= 100

可以nlog排序然后比较diff

也可以o(m) 基数排序,m是数的大小,然后按顺序去diff

class Solution(object):
    def heightChecker(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        count = [0] * 101
        for value in heights:
            count[value] += 1
        index = 0
        ans = 0
        for i in range(101):
            if count[i] == 0:
                continue
            while count[i] > 0:
                if i != heights[index]:
                    ans += 1
                count[i] -= 1
                index += 1
        return ans

 

1051. Height Checker

标签:diff   int   col   dex   bsp   排序   ini   htc   hot   

原文地址:https://www.cnblogs.com/whatyouthink/p/13207858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!