Arrays分类算法-Monotonic Array

题目要求在这里插入图片描述

解法一:
corner case: 排除一开始两元素相等的情况。在判断数组一开始的单增单减情况并记录状态。如果途中状态改变则返回false,如果没有改变,则返回true。
Time: O(n) Space: O(1)
代码:

import java.util.*;

class Program {
  public static boolean isMonotonic(int[] array) {
    // Write your code here.
		if (array == null || array.length <= 1) return true;
		int index = 1;
		while (index < array.length) {
			if (array[index] != array[index - 1]) {
				break;
			}
			index++;
		}
		if (index == array.length) return true;
		boolean status = array[index] - array[index - 1] > 0 ? true : false;
		for (int i = index; i < array.length; i++) {
			
			if (array[i] - array[i - 1] < 0 && status) return false;
			if (array[i] - array[i - 1] > 0 && !status) return false;
			
		}
    return true;
  }
}

解法二:
set两个状态isNonDecreasing 和 isNonIncreasing, 初始化为true,遍历数组,如果出现增减规律变化,则记录两状态也会发生改变。结果返回isNonDecreasing || isNonIncreasing
Time: O(n) Space: O(1)
代码:

import java.util.*;

class Program {
  public static boolean isMonotonic(int[] array) {
    // Write your code here.
		if (array.length <= 2) return true;
	  boolean isNonDecreasing = true;
		boolean isNonIncreasing = true;
		for (int i = 1; i < array.length; i++) {
			
			if (array[i] - array[i - 1] > 0) isNonDecreasing = false;
			if (array[i] - array[i - 1] < 0) isNonIncreasing = false;
				
		}
		return isNonDecreasing || isNonIncreasing;
  }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页