LeetCode 解題練習:Height Checker

Ping-Lun Liao
Feb 19, 2024

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。 If you like this post, please click the ads on the blog or buy me a coffee. Thank you very much.

題目原文描述 https://leetcode.com/problems/height-checker/

中文描述

給定一個整數陣列 heights ,請算出 heights 中沒有依照由小到大之順序的元素個數。

範例一:

輸入 heights = [3, 1, 2]

因為依照小到大的陣列為 [1, 2, 3] ,heights 每個元素皆不再所屬的排序位置上。

範例二:

輸入 heights = [1, 3, 2]

因為依照小到大的陣列為 [1, 2, 3] ,heights[0]有在排序的位置上,其餘元素皆不在所屬的排序位置上。

範例三:

輸入 heights = [1, 2, 3]

因為依照小到大的陣列為 [1, 2, 3] ,heights所有元素皆在所屬的排序位置上。

解法:

先用內建排序函式產生由小排到大的 expected 陣列,依照索引位置 i 算出 heights[i] != expected[i] 有多少個。

Python Code

expected = sorted(heights)

Originally published at https://yunlinsong.blogspot.com.

--

--