我想编写一个程序来计算数组中的重复项.如果两个相同的数字,代码可以工作.但是,如果有三个或更多相同的数字,则会出错.我该怎么办呢?
public class Duplicate
{
public static void main(String[] args)
{
int[] list = new int[]{1,2,3,4,5,6,7,8,8,8,9,10};
int sum = 0;
for(int count=1; count<list.length; count++)
{
if(list[count-1]==list[count])
{
sum = list[count-1] + list[count];
System.out.println("Duplicate found: " + list[count] + " " + "Sum of the duplicate value is " +sum);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种Java-8风格的功能方法:
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 9, 10 };
// Create a Stream<Integer> from your data
IntStream.of(array)
.boxed()
// Group values into a Map<Integer, List<Integer>>
.collect(Collectors.groupingBy(i -> i))
// Filter out those map values that have only 1 element in their group
.entrySet()
.stream()
.filter(e -> e.getValue().size() > 1)
// Print the sum for the remaining groups
.forEach(e -> {
System.out.println(
"Duplicates found for : " + e.getKey() +
" their sum being : " + e.getValue()
.stream()
.collect(Collectors.summingInt(i -> i)));
});
Run Code Online (Sandbox Code Playgroud)
对于您的输入,这会产生:
Duplicates found for : 8 their sum being : 24
Run Code Online (Sandbox Code Playgroud)
这个解决方案的好处在于它适用于无序的解决方案int[].例如......
int[] array = new int[] { 1, 10, 3, 2, 3, 4, 5, 8, 6, 7, 8, 8, 8, 9, 10 };
Run Code Online (Sandbox Code Playgroud)
输出将是......
Duplicates found for : 3 their sum being : 6
Duplicates found for : 8 their sum being : 32
Duplicates found for : 10 their sum being : 20
Run Code Online (Sandbox Code Playgroud)