Algorithm
环路检测
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return null;
}
ListNode fastNode = head.next.next;
ListNode slowNode = head.next;
while (fastNode != slowNode) {
if (fastNode.next == null || fastNode.next.next == null) {
return null;
}
fastNode = fastNode.next.next;
slowNode = slowNode.next;
}
if (fastNode == null) {
return null;
}
fastNode = head;
while (fastNode != slowNode) {
fastNode = fastNode.next;
slowNode = slowNode.next;
}
return fastNode;
}
}
Review
Top 5 Useful Advanced Programming Techniques in Android
写这篇文章的人感觉没做过项目,像是面对刚开发者提供的建议。。。
Tip
Kotlin中集合的none函数:
Kotlin中集合的none()
函数是标准库中的一个函数,它用于检查集合中的元素是否都不符合给定的条件。
函数签名:
fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean
参数:
predicate
:用于检查集合中每个元素的谓词函数。
返回值:
Boolean
类型的值,表示集合中是否不存在符合条件的元素。
如果集合中不存在任何符合条件的元素,则该函数的返回值为true
,反之,则为false
。
例如,假设有以下的集合:
val numbers = listOf(1, 3, 5, 7, 9)
我们可以使用none()
函数来检查集合中是否存在任何奇数:
val result = numbers.none { it % 2 == 0 }
println(result) // 输出 true,因为集合中的所有数字都是奇数
在上面的代码中,none()
函数使用Lambda表达式{ it % 2 == 0 }
来检查集合中的每个元素,并返回true
,表示集合中不存在任何偶数。
需要注意,当集合为空时,none()
函数的返回值为true
,因为不存在任何元素可以匹配到谓词函数。
例如,对于一个空集合:
val emptyList = emptyList<Int>()
val result = emptyList.none { it % 2 == 0 }
println(result) // 输出 true,因为集合为空
这个特性有可能是我们期望得到的行为,但有时候也可能是我们不期望的,需要特别注意。
Share
本周读了《程序是怎样跑起来的》后七章和《计算机组成与设计:硬件_软件接口》前三章。