找出数组中的幸运数
难度:
标签:
题目描述
代码结果
运行时间: 23 ms, 内存: 16.0 MB
/*
* Solution approach using Java Streams:
* 1. Create a frequency map using the stream's collect method and a counting collector.
* 2. Use the entrySet stream to filter entries where the key equals the value (lucky number condition).
* 3. Use the max operation to find the largest lucky number, or return -1 if none exist.
*/
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class LuckyNumberStream {
public int findLucky(int[] arr) {
Map<Integer, Long> frequencyMap = IntStream.of(arr)
.boxed()
.collect(Collectors.groupingBy(num -> num, Collectors.counting()));
return frequencyMap.entrySet().stream()
.filter(entry -> entry.getKey().equals(entry.getValue().intValue()))
.map(Map.Entry::getKey)
.max(Integer::compare)
.orElse(-1);
}
}
解释
方法:
该题解首先使用Counter来统计数组arr中各元素的出现频次,得到一个哈希表。然后,通过一个lambda表达式,检查哈希表中的每个元素(数值)和其对应的频次是否相等。如果相等,则保留该数值,否则返回-1。最后通过max函数从可能的幸运数中选择最大的一个。如果没有找到任何幸运数,max函数将返回-1。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
在这个题解中,为什么选择使用Counter来统计元素频次,而不是其他数据结构如字典或数组?
▷🦆
题解中提到的lambda函数是否有效处理了所有键和值的匹配,特别是当键的顺序与值的顺序不一致时?
▷🦆
解法中如果遇到没有任何幸运数的情况,max函数如何确保返回-1而不是抛出异常?
▷🦆
在题解的逻辑中,有没有可能出现错误或遗漏,例如处理数组中所有元素都相同的特殊情况?
▷