LeetCode(896)--monotone sequence

Article Directory

topic

896. Monotonic sequence
If the array is monotonically increasing or monotonically decreasing, then it is monotonous.
If for all i <= j, A[i] <= A[j], then the array A is monotonically increasing. If for all i <= j, A[i]> = A[j], then the array A is monotonically decreasing.
It returns true when the given array A is a monotonic array, otherwise it returns false.
Example 1:

输入:[1,2,2,3]
输出:true

Example 2:

输入:[6,5,4,4]
输出:true

Example 3:

输入:[1,3,2]
输出:false

Example 4:

输入:[1,2,4,5]
输出:true

Example 5:

输入:[1,1,1]
输出:true

prompt:

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

Problem solution (Java)

class Solution 
{
    
    
    public boolean isMonotonic(int[] A) 
    {
    
    
        //如果A数组的长度为1
        if(A.length == 1)
        {
    
    
            return true;
        }
        //当数组的长度大于1时
        //遍历A数组
        //记录递增的数量
        int upCount = 0;
        //记录递减的数量
        int downCount = 0;
        for(int index = 1;index < A.length;index++)
        {
    
    
            if(A[index] >= A[index - 1])
            {
    
    
                upCount++;
            }
            if(A[index] <= A[index - 1])
            {
    
    
                downCount++;
            }
        }
        //只要为递增或递减数组均可
        return (upCount == A.length - 1 || downCount == A.length - 1);
    }
}

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/114209839