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

LeetCode 2210: Count Hills and Valleys in an Array

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

基本資料
#

難易度: easy 第一次嘗試:2025-07-27

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

解題思路
#

相等的相鄰元素屬於同一個山峰或山谷,所以只看「方向」:每一對相鄰元素是上、下或平(Array 模板一)。平的跳過,記住上一個不平的方向;方向從上變成下就是一個山峰,從下變成上就是一個山谷。

我的解法
#

class Solution:
    def countHillValley(self, nums: List[int]) -> int:
        res, prev = 0, 0                       # prev:上一個不平的方向,1 上、-1 下
        for a, b in zip(nums, nums[1:]):
            d = (b > a) - (b < a)
            if d == 0:
                continue
            if prev and d != prev:
                res += 1
            prev = d
        return res

我當時先把方向存成 "U"、"D"、"T" 的陣列再掃一次,邏輯一樣。

複雜度
#

時間 O(n),空間 O(n)(nums[1:] 的複製)。

要特別避免的錯誤
#

  • 相等的鄰居不能算成新的山峰或山谷,要跳過。

面試口說整理
#

我看每一對相鄰元素的方向,跳過相等的,記住上一個不平的方向;方向改變一次就多一個山峰或山谷。時間 O(n)。

相關文章

LeetCode 3423: Maximum Difference Between Adjacent Elements in a Circular Array
·1 分鐘
LeetCode Easy Array
LeetCode 3423 解題筆記:環狀陣列的相鄰包含最後一個和第一個;用 nums[i - 1] 從 i = 0 開始剛好涵蓋
LeetCode 3550: Smallest Index With Digit Sum Equal to Index
·1 分鐘
LeetCode Easy Math Array
LeetCode 3550 解題筆記:由小到大檢查每個 index,算位數和,第一個相等的就是答案
LeetCode 1979: Find Greatest Common Divisor of Array
·1 分鐘
LeetCode Easy Math Number-Theory Gcd Array
LeetCode 1979 解題筆記:找出最小值和最大值,用輾轉相除法算 GCD
LeetCode 1920: Build Array from Permutation
·1 分鐘
LeetCode Easy Array Simulation
LeetCode 1920 解題筆記:照定義 ans[i] = nums[nums[i]];要 O(1) 額外空間時,把新值乘 n 疊在原本的值上
LeetCode 1304: Find N Unique Integers Sum up to Zero
·1 分鐘
LeetCode Easy Math Array
LeetCode 1304 解題筆記:放 1..n/2 和它們的相反數,兩兩抵銷;n 是奇數時再加一個 0
LeetCode 2094: Finding 3-Digit Even Numbers
·1 分鐘
LeetCode Easy Hash-Table Enumeration Array
LeetCode 2094 解題筆記:反過來枚舉 100 到 998 的偶數,檢查需要的每個數字次數夠不夠;Counter 相減只留正數