2014-04-12 91 views
0

我想從數組中刪除重複(重複)元素。我正面臨着困難。我嘗試了幾種方法。請問任何人都可以爲我找到解決方案。從Int數組中刪除重複(重複)元素

Input: 3,5,6,7,3,5,3,8 
Expected Output: 3 5 6 7 8 

我的代碼:

package com.nanofaroque.DeleteRepElementInArray; 

public class DeleteElementRepetativeElement { 

    public static void main(String[] args) { 
     // Here is the input Array... 
     int[] arr = { 3, 5, 6, 7, 3, 5, 3, 8 }; 
     int end = arr.length;// finding the length of the array 
     for (int i = 0; i < end; i++) { 
      for (int j = i + 1; j < end; j++) { 
       if (arr[j] == arr[i]) { 
        for (int k = j; k < end; k++) { 
         arr[k] = arr[k + 1]; 
        } 
        end--; 
       } else { 
        j++; 
       } 
      } 
     } 
     for (int i = 0; i < arr.length; i++) { 
      System.out.println(arr[i]); 
     } 

    } 

} 
+0

什麼是你期望的輸出? – Braj

+0

預期輸出:3 5 6 7 8 –

+0

所以你想從3,5,3刪除。對? – Braj

回答

1

嘗試org.apache.commons.lang.ArrayUtils

從結束

int[] arr = { 3, 5, 6, 7, 3, 5, 3, 8 }; 
int noOfItemsToBeDeleted=4; 
for (int i = 0; i < noOfItemsToBeDeleted; i++) { 
    if (arr.length > 0) { 
     arr = ArrayUtils.remove(arr, arr.length-1); 
    } 
} 
for (int i : arr) { 
    System.out.println(i); 
} 

刪除開始刪除

int[] arr = { 3, 5, 6, 7, 3, 5, 3, 8 }; 
int noOfItemsToBeDeleted=4; 
for (int i = 0; i < noOfItemsToBeDeleted; i++) { 
    if (arr.length > 0) { 
     arr = ArrayUtils.remove(arr, 0); 
    } 
} 
for (int i : arr) { 
    System.out.println(i); 
} 

- 編輯 -

按你最後的評論,你只想刪除重複值來自一個數組。嘗試使用Set<Integer>刪除重複的值。

int[] arr = { 1, 2, 3, 5, 6, 7, 8, 9, 5, 4, 7, 8, 9, 3, 2, 1, 0, 3, 4, 8 }; 

Set<Integer> set = new LinkedHashSet<Integer>(); 
for (int i : arr) { 
    set.add(i); 
} 

// new array if you need it 
int[] newArray = new int[set.size()]; 
int index = 0; 
for (int i : set) { 
    System.out.print(i+" "); 
    newArray[index++] = i; 
} 

輸出:

1 2 3 5 6 7 8 9 4 0 
+0

它會從開頭或結尾刪除四個元素。這不是我期望的,我正在尋找..謝謝你嘗試 –

+0

你的預期產出是什麼? – Braj

+0

'ArrayUtils'可以幫助你解決這個問題嗎? – Braj