zoukankan      html  css  js  c++  java
  • [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 <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。

    当给定的数组 A 是单调数组时返回 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 }

    LeetCode 题目总结

  • 相关阅读:
    mouseover和mouseenter的区别 mouseenter不会冒泡,mouseleave不会冒泡;
    2021年1月24日 命令按钮控件Button 和 单选按钮控件RadioButton 和复选框按钮
    2021年1月23日 文本框控件
    2021年1月21日 画了个注册的界面
    2021年1月29日 体温上报app03
    2021年1月18日 activity的三种状态
    2021年1月16日 秒表app
    2021年1月15日 界面跳转
    1.CSS知识点——css的引入方式
    面试题 315
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14458064.html
Copyright © 2011-2022 走看看