2015-09-12 128 views
3

我想写一个程序来计算数组中的重复值。如果两个数字相同,代码将起作用。但是,如果有三个或更多相同的号码,则会出现错误。我该如何解决它?计算数组中的重复值

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); 
      } 
     } 
     } 
    } 
+2

究竟是什么“计算重复数字”? – Maroun

+0

输入数组是否总是排序?你期望的输出是什么? – fabian

+0

数组将始终排序? –

回答

4

这将这样的伎俩为您

public static void main(String[] args) 
{ 
    int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 9, 10 }; 

    int sum = 0; 
    for (int j = 0; j < array.length; j++) 
    { 
     for (int k = j + 1; k < array.length; k++) 
     { 
      if (k != j && array[k] == array[j]) 
      { 
       sum = sum + array[k]; 
       System.out.println("Duplicate found: " + array[k] + " " + "Sum of the duplicate value is " + sum); 
      } 
     } 
    } 
} 

希望它能帮助!

8

这里是一个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))); 
     }); 

您的输入,这产生了:

Duplicates found for : 8 their sum being : 24 

关于这个解决方案的好处是,它适用于无序int[]刚一样。例如。为...

int[] array = new int[] { 1, 10, 3, 2, 3, 4, 5, 8, 6, 7, 8, 8, 8, 9, 10 }; 

输出将是...

Duplicates found for : 3 their sum being : 6 
Duplicates found for : 8 their sum being : 32 
Duplicates found for : 10 their sum being : 20 
4

如果你不介意使用Javaslang,集合库为Java 8,这里更多的是一种简洁的解决方案:

int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 9, 10 }; 

// javaslang.collection.List 
List.ofAll(array) 
     .groupBy(i -> i) 
     .entrySet() 
     .filter(e -> e.value.length() > 1) 
     .forEach(e -> { 
      System.out.println(
        "Duplicates found for : " + e.key + 
        " their sum being : " + e.value.sum()); 
     }); 

正如预期的那样,这会产生于:

Duplicates found for : 8 their sum being : 24 

,同样对卢卡斯的回答,对于

int[] array = new int[] { 1, 10, 3, 2, 3, 4, 5, 8, 6, 7, 8, 8, 8, 9, 10 }; 

它产生于

Duplicates found for : 10 their sum being : 20 
Duplicates found for : 8 their sum being : 32 
Duplicates found for : 3 their sum being : 6 

请注意,此代码Javaslang 2.0.0-SNAPSHOT,这是即将发布运行。