@azurefrog给出了很好的答案了。下面是计算有一个给定数量超过3项对实现:
List<Integer> numbers = Arrays.asList(2, 3, 2, 3, 2, 2, 9);
Map<Integer, Long> map = numbers.stream()
.collect(Collectors.groupingBy(num -> num, Collectors.counting()))
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue()/2));
// output
map.forEach((num, count) -> System.out.println(String.format("%d has %d unique pairs", num, count)));
Long total = map.values().stream().reduce((acc, c) -> c + acc).get();
System.out.print(String.format("A total of %d pairs", total));
考虑到在评论中列出的其他限制:没有对矫正原始数据,简单的循环,只是“简单”的数据结构;
一种方法是跟踪你是否见过一个元素(我做这个用布尔数组):
int[] hand = {2,3,2,3,2,9,5,5,5,5,5,5,5};
boolean[] hasPair = new boolean[10];
for(int i = 0; i <= hand.length - 2 ; i++) {
for(int j= i + 1; j <= hand.length - 1; j++) {
if (hand[j] == hand[i]) {
hasPair[hand[j]] = true;
}
}
}
int count = 0;
for (boolean b : hasPair) {
if (b) {
count += 1;
}
}
System.out.print(count);
这计数独特的双或“复制”,假定输入数组为int的在{1,...,9}
来源
2017-02-12 04:42:51
Nic
数字是否有合理的界限?就像,他们都是1到100之间的整数或者什么? –
我不认为你实际上需要构建所有的对来解决你的问题,如果它只是一个数。如果将数组转换为映射条目到出现次数的“Map”,那么floor(count/2)应该给出每个数字对的数目no? –
Nic
更多的上下文,在这个特定的情况下,我被限制在从1-9范围内的五个值的数组。还试图用循环等基本技术来解决,因为我还没有进入更高级的主题 – tmoesabi