Prompt
Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic.
An array is said to be monotonic if its elements, from left to right, are entirely nonincreasing or entirely non-decreasing.
Sample Input
arrag = [-1, -5, -10, -8020}
Sample Output
true
Solution 1
import java.util.*;
class Program {
// O(n) time | O(1) space
public static boolean isMonotonic(int[] array) {
// Write your code here.
var isNonDecreasing = true;//B
var isNonIncreasing = true;//C
for (int i = 1; i < array.length ;i++ ) {
if (array[i] > array[i - 1]) {
isNonIncreasing = false;
}
if (array[i] < array[i - 1]) {
isNonDecreasing = false;
}
}
return isNonDecreasing || isNonIncreasing; //A
}
}
# 1A
有两种结果,这种思路会很简洁
# 1B
isNonDecresing 命名包含了相等的情况
# 1C
Solution 2
import java.util.*;
class Program {
// O(n) time | O(1) space
public static boolean isMonotonic(int[] array) {
if (array.length <= 2) return true;//A
// Write your code here.
var direction = array[1] - array[0];
for (int i = 2; i < array.length ;i++ ) {
if (direction == 0) {//B
direction = array[i] - array[i - 1];
continue;
}
if (breakDirection(direction, array, i)) return false;//C
}a
return true;
}
public static boolean breakDirection(int direction, int[] array, int i) {
int difference = array[i] - array[i - 1];
if (direction > 0) return difference < 0;
return difference > 0;
}
}
# 2A
数组的题目 要考虑数组的长短
# 2B
见识的太少了 不要想当然
# 2C
把if的wet语句,用这种方式写进辅助函数里