2017-04-07 105 views
1

我想從Java中的數組中刪除每個重複項,並將剩餘的整數存儲在同一個數組中。如何刪除數組中的所有重複項

例如:int [] = {5,5,5,3,4,4,2,2,1}; ==> int [] = {3,1};

到目前爲止,我已經嘗試使用:

Set<Integer> set = new HashSet<Integer>(); 

for (int i = 0; i < array.length; i++) { 
    set.add(array[i]); 
} 

看起來雖然,這只是刪除重複的一個而不是兩個。

任何幫助,將不勝感激。

+0

的可能的複製[獲得從在Java ArrayList中唯一值](http://stackoverflow.com/questions/13429119/get-unique-values-from-arraylist -in-java) – Okapist

+0

@Marc H.我編輯了我的代碼,你可以測試一下。 – Alekhya

+0

請添加更多的上下文。您現在所顯示的是一個循環,它將元素添加到集合中。那又怎麼樣? – Arkadiy

回答

0

這應該工作:

INT []數組= {5,5,5,3,4,4,2,2,1};

Arrays.sort(array); 
Set<Integer> set = new HashSet<Integer>(); 

Set<Integer> duplicateSet = new HashSet<Integer>(); 

for (int i = 0; i < array.length; i++) { 

    if(!set.add(array[i])){ 
     duplicateSet.add(array[i]); 
    } 
} 


System.out.println(duplicateSet.toString()); 
set.removeAll(duplicateSet); 
System.out.println(set.toString()); 

輸出:

[1,3] 
+4

如果有奇數的重複項,這將不起作用 – prasanth

+0

我編輯了我的代碼。 – Alekhya

0

您可以使用HashMap,維護每個元素的數量並刪除那些具有元素計數大於1

public int[] removeDuplicates(int[] arr) { 
    Map<Integer, Integer> countMap = new LinkedHashMap<>(); // To maintain the order 
    for (int n : arr) { 
     Integer count = countMap.get(n); 
     if (count == null) { 
     count = 0; 
     } 
     count++; 
     countMap.put(n, count); 
    } 

    for(Iterator<Map.Entry<String, String>> it = countMap.entrySet().iterator(); it.hasNext();) { 
     Map.Entry<String, String> entry = it.next(); 
     if (entry.getValue() > 1) { 
     it.remove(); 
     } 
    } 

    return new ArrayList<>(countMap.keySet()).toArray(new int[0]); 
} 
0

你不即使是一套,也非常簡單,將數組轉換爲列表,然後使用Collections.frequency檢查重複項,如下所示:

Integer[] array = { 5,5,5,3,4,4,2,2,1}; 
    List<Integer> listInputs = Arrays.asList(array); 
    List<Integer> listOutputs = new ArrayList<>(); 
    for(int value : listInputs) { 
     if(Collections.frequency(listInputs, value) ==1) { 
      listOutputs.add(value); 
     } 
    } 
    System.out.println(listOutputs); 

OUTPUT:[3,1]

+0

感謝您的回答。可悲的是我總是收到以下警告:類型列表不是通用的;它不能使用參數進行參數化

+0

您是否使用過上述更新後的代碼? – developer

+0

這是個好主意。但'Collections.frequency()'有一個'O(n)'的運行時間,這是壞的。這段代碼的總運行時間爲'O(n^2)'。 – prasanth