896.Montonic Array

Question

896. Monotonic Array

Solution

题目大意:

类似于数学中的减函数,增函数和物理中的加速度为正或为负

思路:

先比较前两个是大于0还是小于0,如果等于0就比较第2,3两个,依次类推,得到这个是递增数组还递减数组后再遍历接下来的数就好办了

Java实现:

public boolean isMonotonic(int[] A) {
    if (A.length == 1) return true;
    int compFlag = 0;
    int i = 1;
    while (compFlag == 0 && i < A.length) {
        compFlag = A[i] - A[i - 1];
        i++;
    }
    while (compFlag > 0 && i < A.length) {
        if (A[i] - A[i - 1] < 0) return false;
        i++;
    }
    while (compFlag < 0 && i < A.length) {
        if (A[i] - A[i - 1] > 0) return false;
        i++;
    }

    return true;
}
原文地址:https://www.cnblogs.com/okokabcd/p/9615029.html