LeetCode—896

Approach

# 確認數列是遞增還是遞減
Check the monotonic is increasing or decreasing.

# 變數只能改一次
Variable can be change only one time.

Time Complexity

# n = length of nums
O(n)

Space Complexity

# n = 1
O(1)

Code

class Solution {
public:
    bool isMonotonic(vector<int>& nums) {
        int l = nums.size(), before = 0;

        if (l == 1) {
            return true;
        }

        if (nums[1] - nums[0] > 0) {
            before = 1;
        }
        else if (nums[1] - nums[0] < 0) {
            before = -1;
        }
        else {
            before = 0;
        }

        for (int i = 2 ; i < l ; i++) {
            if (nums[i] - nums[i - 1] > 0) {
                if (before == -1) {
                    return false;
                }
                else {
                    if (before == 0) {
                        before = 1; 
                    }
                }
            }
            else if (nums[i] - nums[i - 1] < 0) {
                if (before == 1) {
                    return false;
                }
                else {
                    if (before == 0) {
                        before = -1;
                    }
                }
            }
        }

        return true;
    }
};