Skip to content

LeetCode: 941-Valid Mountain Array 解題紀錄

Last Updated on 2022-01-25 by Clay

題目

Given an array of integers arr, return true if and only if it is a valid mountain array.

Recall that arr is a mountain array if and only if:
  • arr.length >= 3
  • There exists some i with 0 < i < arr.length - 1 such that:
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Example 1:

Input: arr = [2,1]
Output: false

Example 2:

Input: arr = [3,5,5]
Output: false

Example 3:

Input: arr = [0,3,2,1]
Output: true

Constraints:

  • 1 <= arr.length <= 104
  • 0 <= arr[i] <= 104

題目給定一組正整數陣列,要判斷這正整數陣列是否符合『山』的形狀。

也就是說陣列剛開始一定要逐步遞增、到了某個點後一定要逐步遞減;需要注意的是兩相鄰的數字相等就不算是山的形狀。


解題思路

首先我判斷陣列長度是否小於 2,小於 2 的情況一定無法組成山的形狀。

之後則開始判斷是否有開始往上增長、如果遇到第一個減少的數值,則轉為判斷是否一直減少。

這題非常單純,基本不存在陷阱,只要判斷寫對,基本上走完就知道答案了。


複雜度

Time ComplexityO(n)
Space ComplexityO(1)


C++ 範例程式碼

class Solution {
public:
    bool validMountainArray(vector<int>& arr) {
        // Base case
        if (arr.size() <= 2) return false;
        
        // Init
        int i = 1;
        bool up = false;
        bool down = false;
        
        // Up
        while (i < arr.size()) {
            if (arr[i] == arr[i-1]) return false;
            else if (arr[i] > arr[i-1]) up = true;
            else if (arr[i] < arr[i-1]) break;
            ++i;
        }
        
        // If never increasing, it is not a valid mountain array!
        if (!up) return false;
        
        // Down
        while (i < arr.size()) {
            if (arr[i] == arr[i-1]) return false;
            else if (arr[i] < arr[i-1]) down = true;
            else if (arr[i] > arr[i-1]) return false;
            ++i;
        }
        
        // If never decreasing, it is not a valid mountain array either.
        if (!down) return false;
        
        // Valid
        return true;
    }
};



Python 範例程式碼

class Solution:
    def validMountainArray(self, arr: List[int]) -> bool:
        # Base case
        if len(arr) <= 2: return False
        
        # Init
        i = 1
        up = False
        down = False
        
        # Up
        while i < len(arr):
            if arr[i] == arr[i-1]: return False
            elif arr[i] > arr[i-1]: up = True
            elif arr[i] < arr[i-1]:
                down = True
                i += 1
                break
            
            i += 1
        
        # If never increasing, it is not a valid mountain array!
        if not up: return False
        
        # Down
        while i < len(arr):
            if arr[i] == arr[i-1]: return False
            elif arr[i] < arr[i-1]: down = True
            elif arr[i] > arr[i-1]: return False
            i += 1
        
        # If never decreasing, it is not a valid mountain array either.
        if not down: return False
        
        # Valid
        return True

References


Read More

Leave a Reply