[LeetCode] 896. Monotonic Array

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array A is monotone increasing if for all i <= jA[i] <= A[j].  An array A is monotone decreasing if for all i <= jA[i] >= A[j].

Return true if and only if the given array A is monotonic.

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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

Note:

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

单调数列。

如果数组是单调递增或单调递减的,那么它是 单调 

如果对于所有 i <= jnums[i] <= nums[j],那么数组 nums 是单调递增的。 如果对于所有 i <= jnums[i]> = nums[j],那么数组 nums 是单调递减的。

当给定的数组 nums 是单调数组时返回 true,否则返回 false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/monotonic-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

[一刷,做法很垃圾] 一开始我想通过判断第一个和第二个元素之间的大小关系来定义 input 数组到底是单调增还是单调减,后来发觉是行不通的,因为数组里面两个相邻数字之间如果是相等的,也是需要返回 true 的。这道题正确的做法是确保数组内单调增的次数和单调减的次数不能同时不为 0。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public boolean isMonotonic(int[] A) {
 3         int len = A.length;
 4         // corner case
 5         if (len <= 1) {
 6             return true;
 7         }
 8         // normal case
 9         int up = 0;
10         int down = 0;
11         for (int i = 1; i < len; i++) {
12             if (A[i] - A[i - 1] > 0) {
13                 up++;
14                 if (down != 0) {
15                     return false;
16                 }
17             } else if (A[i] - A[i - 1] < 0) {
18                 down++;
19                 if (up != 0) {
20                     return false;
21                 }
22             }
23         }
24         return true;
25     }
26 }

 

[二刷] 思路是写两个 helper 函数,一个判断是否是单调增,一个判断是否是单调减,有一个返回 true,整个程序就能返回 true。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public boolean isMonotonic(int[] nums) {
 3         if (increase(nums) || decrease(nums)) {
 4             return true;
 5         }
 6         return false;
 7     }
 8 
 9     private boolean increase(int[] nums) {
10         for (int i = 1; i < nums.length; i++) {
11             if (nums[i] < nums[i - 1]) {
12                 return false;
13             }
14         }
15         return true;
16     }
17 
18     private boolean decrease(int[] nums) {
19         for (int i = 1; i < nums.length; i++) {
20             if (nums[i] > nums[i - 1]) {
21                 return false;
22             }
23         }
24         return true;
25     }
26 }

 

LeetCode 题目总结

posted @ 2021-02-28 07:29  CNoodle  阅读(89)  评论(0编辑  收藏  举报