Height Checker
- 题目描述:返回未站在正确位置的学生的最小人数。
- 思路:先对原输入数组排序,再将排序后的数组与原数组做比较,统计它们对应元素不相等的个数即可。
- code:
class Solution:
def heightChecker(self, heights: List[int]) -> int:
temp = heights.copy()
temp.sort()
res = [1 for x, y in zip(heights, temp) if x != y]
return len(res)
- 总结:记录该题目,并非是因为题目本身具有什么代表性,而是通过提交结果发现python一些因为写法不同而造成的性能问题,比如上述代码中: (1). 先对数组进行浅copy,再进行排序。(2). 先创建list对象存放结果,再求长度。这个两个细节问题,直接决定了提交的结果,深入原因以后再总结,特此记录。