如果您想将索引迭代为一个范围,您可以使用IntArray 的属性lastIndex 以避免IndexOutOfBoundsException。
只是不要将一个元素与其后继元素进行比较,从第二个元素开始,并在从索引 1 迭代到最后一个索引时将其前身与它进行比较,如下所示:
fun isMonotonic(A: IntArray): Boolean {
var increasing : Boolean = false
var decreasing : Boolean = false
// iterate the range from 1 to the last index, starting with the second index
for (i in 1..A.lastIndex) {
val predecessor = A[i - 1]
val successor = A[i]
if (predecessor < successor) {
increasing = true
println("${predecessor} < ${successor}")
} else if (predecessor > successor) {
decreasing = true
println("${predecessor} > ${successor}")
} else {
println("${predecessor} = ${successor}")
}
// check if you can exit already (current state is not monotonic)
if (increasing && decreasing) {
return false;
}
}
// if no intermediate state was "not monotonic", this must be "monotonic"
return true;
}
或像这样(感谢您的评论,@AnimeshSahu):
fun isMonotonic(A: IntArray): Boolean {
var increasing : Boolean = false
var decreasing : Boolean = false
// iterate the range from 0 to the second last index
for (i in 0 until A.lastIndex) {
val predecessor = A[i]
val successor = A[i + 1]
if (predecessor < successor) {
increasing = true
println("${predecessor} < ${successor}")
} else if (predecessor > successor) {
decreasing = true
println("${predecessor} > ${successor}")
} else {
println("${predecessor} = ${successor}")
}
// check if you can exit already (current state is not monotonic)
if (increasing && decreasing) {
return false;
}
}
// if no intermediate state was "not monotonic", this must be "monotonic"
return true;
}
我已经尝试过以下方式:
fun main() {
var arr = intArrayOf(1, 2, 3, 4, 5, 6, 7)
if (isMonotonic(arr)) {
println("monotonic")
} else {
println("not monotonic")
}
}
这给了我输出
1 < 2
2 < 3
3 < 4
4 < 5
5 < 6
6 < 7
monotonic
而intArrayOf(1, 2, 3, 4, 3, 2, 1) 的输入导致
1 < 2
2 < 3
3 < 4
4 > 3
not monotonic
输入 intArrayOf(1, 2, 3, 4, 4, 4, 4) 带来了输出
1 < 2
2 < 3
3 < 4
4 = 4
4 = 4
4 = 4
monotonic