首页 > 解决方案 > 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});
                }
        }

标签: java

解决方案


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.


推荐阅读