@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