1051. Height Checker

Posted whatyouthink

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1051. Height Checker相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

1051. Height Checker

LeetCode --- 1051. Height Checker 解题报告

1051. Height Checker

Leetcode1051Height Checker

LEETCODE401051. Height Checker

算法leetcode1051. 高度检查器(rust和go)