[LeetCode] 896. Monotonic Array

原题链接:https://leetcode.com/problems/monotonic-array/

1. 题目介绍

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].
单调递增的定义是,对于所有的 i <= j, 都有A[i] <= A[j],单调递减的定义是,对于 所有 i <= j, 都有A[i] >= A[j].
Return true if and only if the given array A is monotonic.
当且仅当数组A是单调时,返回true,否则返回false

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 <= A.length <= 50000
-100000 <= A[i] <= 100000

2. 解题思路

这个题的解题方法有很多,我一开始最先想到的方法就是先找到第一个递增或者递减的数,把递增还是递减的情况记录下来,然后判断它后面的数是否递增或者递减,并且在后面循环的时候,要更新以前保存的递增/递减情况。
但是我的代码不够简洁,因此这里就直接放上题目中Solution的代码吧,他的代码方法和我一样,但是比我的简洁多了.

class Solution {
    public boolean isMonotonic(int[] A) {
        int store = 0;
        for (int i = 0; i < A.length - 1; ++i) {
            int c = Integer.compare(A[i], A[i+1]);
            if (c != 0) {
                if (c != store && store != 0)
                    return false;
                store = c;
            }
        }
        return true;
    }
}

我看了所有代码中,时间最快的那个代码,它是这样处理的:
先比较最后一个数和第一个数。
如果第一个数小于最后一个数,那么这个数组就可能是递增的,于是遍历整个数组,如果发现有比前一个数小,那么就返回false,否则整个数列就是单调递增的。
如果第一个数大于最后一个数,那么这个数组就可能是递减的,于是遍历整个数组,如果发现有比前一个数大,那么就返回false,否则整个数列就是单调递减的。
时间复杂度也是O(n)
实现代码

class Solution {
    public boolean isMonotonic(int[] A) {
		int length = A.length;
		if (length == 0) {
			return false;
		}
        int flag = (A[length-1] > A[0] ? 1 : 2 );
        if (flag == 1) {
        	for (int i = 0; i<length-1 ; i++) {
        		if (A[i] > A[i+1]) {
        			return false;
        		}
        	}
        }else{
        	for (int i = 0; i<length-1 ; i++) {
        		if (A[i] < A[i+1]) {
        			return false;
        		}
        	}
        }
        return true;
    }
}

当然,Solution给出的这个方法也不错,只不过它必须要完整遍历完全部的数组才能给出结果。而上面两种方法是遇到第一个不单调的数字就会跳出循环了。

class Solution {
    public boolean isMonotonic(int[] A) {
        boolean increasing = true;
        boolean decreasing = true;
        for (int i = 0; i < A.length - 1; ++i) {
            if (A[i] > A[i+1])
                increasing = false;
            if (A[i] < A[i+1])
                decreasing = false;
        }
        return increasing || decreasing;
    }
}

3. 参考链接

https://leetcode.com/problems/monotonic-array/solution/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值