可能值得将频率存储在一组排序的映射条目中,然后更容易找到具有最大频率的元素,使用 Java 9 Stream::dropWhile 跳过具有此频率的元素并拾取下一个元素。
public static int secondMostRepeatable(int ... arr) {
Set<Map.Entry<Integer, Integer>> freq = Arrays.stream(arr)
.boxed()
.collect(Collectors.groupingBy(x -> x, Collectors.summingInt(x -> 1)))
.entrySet().stream()
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
.collect(Collectors.toCollection(LinkedHashSet::new));
System.out.print(freq); // debug print
int max = freq.iterator().hasNext() ? freq.iterator().next().getValue() : -1;
System.out.print("; max freq=" + max + " "); // debug print
return freq.stream()
.dropWhile(e -> e.getValue() == max)
.findFirst()
.map(Map.Entry::getKey)
.orElse(-1);
}
测试:
System.out.println(secondMostRepeatable());
System.out.println(secondMostRepeatable(1));
System.out.println(secondMostRepeatable(1, 1, 1));
System.out.println(secondMostRepeatable(1, 2, 3, 4));
System.out.println(secondMostRepeatable(1, 2, 2, 3, 4));
System.out.println(secondMostRepeatable(1, 2, 2, 2, 3, 3, 4));
输出
[]; max freq=-1 -1
[1=1]; max freq=1 -1
[1=3]; max freq=3 -1
[1=1, 2=1, 3=1, 4=1]; max freq=1 -1
[2=2, 1=1, 3=1, 4=1]; max freq=2 1
[2=3, 3=2, 1=1, 4=1]; max freq=3 3