• [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 题目总结

  • 相关阅读:
    Nginx原理入门教程
    MSDN原版系统镜像ISO下载站
    JWT跨域身份验证解决方案
    PHP获取毫秒时间戳
    IDCode校验算法
    PurpleAir空气质量数据采集
    检测微信好友是否删除自己
    京东联盟开发(13)——获取官方活动推广数据
    微信二维码标准
    车牌号正则表达式
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14458064.html
Copyright © 2020-2023  润新知