Java 判断数组是否单调不减:代码实现与详解
以下是一个判断一个数组是否为单调不减的 Java 代码:
public class Main {
public static boolean isMonotonic(int[] array) {
// 如果数组长度小于等于1,直接返回true
if (array.length <= 1) {
return true;
}
// 初始化标志位
boolean increasing = true;
boolean decreasing = true;
// 遍历数组
for (int i = 1; i < array.length; i++) {
// 如果当前元素小于前一个元素,则不是单调不减的
if (array[i] < array[i - 1]) {
increasing = false;
}
// 如果当前元素大于前一个元素,则不是单调不减的
if (array[i] > array[i - 1]) {
decreasing = false;
}
}
// 返回判断结果
return increasing || decreasing;
}
public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {5, 4, 3, 2, 1};
int[] array3 = {1, 3, 2, 4, 5};
System.out.println(isMonotonic(array1)); // 输出 true
System.out.println(isMonotonic(array2)); // 输出 true
System.out.println(isMonotonic(array3)); // 输出 false
}
}
代码中的isMonotonic方法接受一个整型数组作为参数,通过遍历数组的方式判断该数组是否为单调不减的。如果数组长度小于等于1,则直接返回true。遍历数组时,如果当前元素小于前一个元素,则将increasing标志位设为false;如果当前元素大于前一个元素,则将decreasing标志位设为false。最后,返回increasing或decreasing的逻辑或结果作为判断数组单调性的结果。
原文地址: https://www.cveoy.top/t/topic/bO7y 著作权归作者所有。请勿转载和采集!