Re: [閒聊] 每日leetcode

作者: sustainer123 (caster)   2024-06-10 09:23:54
https://leetcode.com/problems/height-checker
1051. Height Checker
給定一數列heights 我們期待heights是一非遞減數列
此理想數列設為expected
請回傳heights[i] != expected[i]的數量
Example 1:
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
heights: [1,1,4,2,1,3]
expected: [1,1,1,2,3,4]
Indices 2, 4, and 5 do not match.
Example 2:
Input: heights = [5,1,2,3,4]
Output: 5
Explanation:
heights: [5,1,2,3,4]
expected: [1,2,3,4,5]
All indices do not match.
Example 3:
Input: heights = [1,2,3,4,5]
Output: 0
Explanation:
heights: [1,2,3,4,5]
expected: [1,2,3,4,5]
All indices match.
Constraints:
1 <= heights.length <= 100
1 <= heights[i] <= 100
思路:
排序
Python Code:
class Solution:
def heightChecker(self, heights: List[int]) -> int:
n = sorted(heights)
result = 0
for i in range(len(n)):
if n[i] != heights[i]:
result += 1
return result
看解答好像能把時間複雜度降到n 等等研究一下
作者: DJYOSHITAKA (Evans)   2024-06-10 09:57:00
bucket吧 但我好懶

Links booklink

Contact Us: admin [ a t ] ucptt.com