Nee*_*eeK 3 functional-programming kotlin
我正在寻找一种最好的方法来迭代 IntArray 索引类似于下面的 JAVA 代码
for (int i = 0; i < arr.length - 1; i++)
Run Code Online (Sandbox Code Playgroud)
我正在使用下面的代码,我不想迭代最后一个元素来避免IndexOutOfBoundException
. A.indices
允许我迭代所有索引,而我不想像上面那样触摸最后一个元素:
class Solution {
fun isMonotonic(A: IntArray): Boolean {
var increasing : Boolean = false
var decreasing : Boolean = false
for (i in A.indices) {
if (A[i] <= A[i+1]) increasing = true
if (A[i] >= A[i+1]) decreasing = true
}
return increasing && decreasing
}
}
Run Code Online (Sandbox Code Playgroud)
具有不可变变量的函数方法之一。请注意,数组没有zipWithNext
因此必须转换成Sequence
第一
fun isMonotonic(A: IntArray): Boolean {
val list = A.asSequence().zipWithNext()
return !list.any { it.first < it.second } || !list.any { it.first > it.second }
}
Run Code Online (Sandbox Code Playgroud)
根据@sschuberth 的评论进行编辑,将 List 替换为 Sequence 以获得更好的性能。
归档时间: |
|
查看次数: |
650 次 |
最近记录: |