java - Find Integer in Array - 使用函数式编程简化解决方案
问题描述
我正在解决各种难题。再一次,我想到了使用函数式编程进行简化。
要解决的问题是:给定一个整数数组 arr,幸运整数是一个整数,它在数组中的频率等于它的值。返回数组中的幸运整数。如果有多个幸运整数,则返回其中最大的一个。如果没有幸运整数返回-1。.
我发现我的解决方案在这里既麻烦又复杂,有没有更简单的方法来解决这个问题?(也许使用 lambda 的)
import java.util.*;
public class FindLucky {
public static int findLucky(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
Set<Integer> set = new TreeSet<>();
for (Integer i : arr) {
if (map.containsKey(i)) {
map.replace(i, map.get(i) + 1);
} else {
map.put(i, 1);
}
}
for (Integer key : map.keySet()) {
if (key == map.get(key)) {
set.add(key);
}
}
if (set.size() < 1) {
return -1;
}
return Collections.max(set);
}
public static void main(String... args) {
findLucky(new int[]{1, 2, 2, 3, 3, 3});
findLucky(new int[]{2, 2, 2, 3, 3});
findLucky(new int[]{5});
}
}
解决方案
Stream-based solution may look as follows:
static int findLucky(int[] arr) {
return Arrays.stream(arr)
.boxed() // convert to Integer
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) // group by number, count frequencies
.entrySet().stream()
.filter(e -> e.getKey().intValue() == e.getValue().intValue()) // select lucky candidates
.mapToInt(e -> e.getKey().intValue())
.max().orElse(-1);
}
The complexity of this solution is linear.
推荐阅读
- python - 使用 Python 中的 sqlalchemy 和 Microsoft Access 驱动程序的 InterfaceError
- vb.net - 如何从 Visual Studio 将新记录添加到 Access 数据库。(VB.NET)
- html - 让 ul 列表看起来更好,无论 li 的身高如何
- kotlin - 我怎样才能避免重复的 else 分支?
- sql - 在 ORACLE 中查找帐户的活动天数
- java - 当应用程序从最近的 android 中清除时无法获得 sinch 呼叫
- azure - 持久的 Azure 函数和集成测试
- ionic-framework - 'ModalController' 类型上不存在属性 'dismiss'
- c - 通过成员为动态数组的函数初始化结构
- stata - 为什么我会收到类型不匹配错误消息?