2013-05-20 33 views
-4

我想從數組中使用方法刪除重複的數字,但不幸的是我無法解決它。這是我迄今爲止所做的:使用方法刪除數組中的重複項

//method code 
public static int[] removeDuplicates(int[] input){ 
    int []r=new int[input.length]; 

    for (int i = 0; i < input.length; i++) { 
     for (int j = 0; j < input.length; j++) { 
      if ((input[i]==input[j]) && (i != j)) { 
       return r; 
      } 
     } 
    } 
    return r; 
} 
+1

您正在查找[Set](http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html)和'contains'方法。 – 2013-05-20 23:06:34

+1

你知道如何添加元素到數組嗎? – mre

+0

你想創建自己的方法來刪除重複項嗎?否則,正如MichaelIT所說,你可以使用set,其中set不允許重複的項目。 – Smit

回答

1

最簡單的事情就是添加一個集合中的所有元素。

public static int[] removeDuplicates(int[] input){ 
    Set<Integer> set = new HashSet<Integer>(); 
    for (int i = 0; i < input.length; i++) { 
     set.add(input[i]); 
    } 
    //by adding all elements in the Set, the duplicates where removed. 
    int[] array = new int[set.size()]; 
    int i = 0; 
    for (Integer num : set) { 
     array[i++] = num;   
    } 
    return array; 
} 
+0

這將改變元素的順序,這可能會或可能會不成問題。 – Thilo

+0

你是對的。 – nakosspy

+0

謝謝@ nakosspy,但我需要解決它沒有**設置**什麼其他方式 –

1

你可以這樣來做:

public static int[] removeDuplicates(int[] input){ 
    boolean[] duplicate = new boolean[input.length]; 
    int dups = 0; 
    for (int i = 0; i < input.length; i++) { 
     if(duplicate[i]) 
      continue; 
     for (int j = i + 1; j < input.length; j++) { 
      if ((input[i]==input[j])) { 
       duplicate[j] = true; // j is duplicate 
       ++dups; 
      } 
     } 
    } 
    int[] r = new int[input.length] - dups; 
    int index = 0; 
    for(int i = 0; i < input.length; ++i) 
     r[index++] = input[i]; 
    return r; 
} 

它也可以在O(n log n)完成。 C++ code

0

如果你不想在你的集合中有重複,那麼你不應該首先使用數組。使用一套,而不會重複首先刪除。

如果你只是「有時」不想重複,那麼你最好進一步解釋你的情況。

+1

「如果你不想在你的收藏中出現重複,那麼你應該首先不要使用數組。」這就像是說「如果你需要命令行參數是整數,你不應該使用'main(String [] argv)'」。有* input data *之類的東西,它並不總是以最方便的方式出現。 – Thilo

+0

確實如此,有時會以不能約束的格式輸入數據。但是這些情況比你想象的要少,應儘可能避免。 – Sonarpulse

+0

同樣適用於輸出限制。 – Sonarpulse