2015-09-12 124 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,這是即將發佈運行。