jotting

ⓁⒸ ‧‧‧ 896. Monotonic Array

896. Monotonic Array

❀ Origin

Problem

An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j].
An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.

Note

  1. 1 <= A.length <= 50000
  2. -100000 <= A[i] <= 100000

Example 1

1
2
Input: [1,2,2,3]
Output: true

Example 2

1
2
Input: [6,5,4,4]
Output: true

Example 3

1
2
Input: [1,3,2]
Output: false

Example 4

1
2
Input: [1,2,4,5]
Output: true

Example 5

1
2
Input: [1,1,1]
Output: true

❀ 翻譯

問題

如果是單調的遞增或單調遞減,則這是個單調陣列
如果所有 i <= j, A[i] <= A[j] ,則 A 陣列為單調。
如果所有 i <= j, A[i] >= A[j] ,則 A 陣列為單調。
只有當給定的陣列 A 為單調時,才回傳 true

注意

  1. 1 <= A.length <= 50000
  2. -100000 <= A[i] <= 100000

❀ Solution

Golang

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package problem0896

/**
* 判斷是否為單調的數列(統一遞增、遞減、不變)
* 解題方向為:
* 從 A 第一個數字,往後遍歷一次 A ,
* 將當前數和之前一數字相比,判斷為增加還是減少,
* 當 increasing, decreasing 都變成 false 時,
* 則代表為不單調數列,故即可回傳 false
* 都為單調即回傳 true
*/
func isMonotonic(A []int) bool {
increasing, decreasing := true, true
for i := 1; i < len(A); i++ {
switch {
case A[i] > A[i-1]:
decreasing = false
case A[i] < A[i-1]:
increasing = false
}

if decreasing == false && increasing == false {
return false
}
}
return true
}