↓快轉到主要內容
  1. LeetCode/

LeetCode 1051: Height Checker

·1 分鐘· ·
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-09-30

  • 提交紀錄:Accepted(一次通過)

解題思路
#

期望的順序就是排序後的陣列,比較兩個陣列有幾個位置不同。高度只有 1..100,也可以用計數排序做到 O(n + 100)(Bucket Sort)。

我的解法
#

class Solution:
    def heightChecker(self, heights: List[int]) -> int:
        return sum(a != b for a, b in zip(heights, sorted(heights)))

複雜度
#

時間 O(n log n),空間 O(n)。

要特別避免的錯誤
#

  • 用 sorted 產生新的陣列,不要原地排序原本的。

面試口說整理
#

期望的順序就是排序後的結果,我把排序後的陣列跟原本的逐一比較,數不同的位置。時間 O(n log n),用計數排序可以到線性。

相關文章

LeetCode 561: Array Partition
·1 分鐘
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 解題筆記:排序後相鄰兩個一組,每組的最小值就是偶數位置的數,加總
LeetCode 594: Longest Harmonious Subsequence
·1 分鐘
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 解題筆記:子序列不用連續,所以只要計數,每個 x 看 x 和 x + 1 的次數加起來
LeetCode 506: Relative Ranks
·1 分鐘
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 解題筆記:把 index 按分數由高到低排序,前三名給獎牌,其他給名次的字串,放回原本的位置
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 1005: Maximize Sum Of Array After K Negations
·1 分鐘
LeetCode Easy Array Greedy Sorting
LeetCode 1005 解題筆記:每次把最小的數變號;最小的已經是正數時,剩下的次數只要看奇偶
LeetCode 977: Squares of a Sorted Array
·1 分鐘
LeetCode Easy Array Two-Pointers Sorting
LeetCode 977 解題筆記:平方後最大的一定在兩端,左右指針比較兩端的平方,大的從結果的最後面往前填