網頁

2024年6月10日 星期一

Python C++計數排序與一行解Leetcode 1051 Height Checker


套用系統排序函數解當然簡單,自己造輪子就稍微進階點,觀察輸入資料限制,counting sort應該是可以自造又不失為簡單且線性時間的解答。

Python C++計數排序與一行解Leetcode 1051  Height Checker
Python 1 行解以及
計數排序的解,它使用計數排序並重複使用heights來存原始陣列和排序後的差異;然後使用 |heights|-count(heights, 0) 給出答案。 C++ 和 python 程式碼都已製作。
一行解請進
------------------------
Python 1-liner
A variant for Counting sort which uses counting sort & reuse the array heights to hold the difference of original & sorted ones; then use |heights|-count(heights, 0) to give the answer. Both C++ & python codes are made.
class Solution:
    def heightChecker(self, heights: List[int]) -> int:
        return sum(h!=s for h, s in zip(heights, sorted(heights)))

沒有留言:

張貼留言

HTML 編輯器