2011-06-07 22 views

回答

4

聽起來就像你想要使用一套。這將清除所有重複的條目,但你也可以只創建具有獨特的條目(沒有空值)的數組

String[] array = 
Set<String> found = new LinkedHashSet<String>(); 
for(int i=0;i<array.length;i++) 
    if(!found.add(array[i])) 
     array[i] = null; 

// just the entries without duplicates. 
String[] unique = found.toArray(new String[found.size()]); 
+0

爲什麼「連接」?.. – aioobe 2011-06-07 08:41:14

+0

@aioobe。在從集合中獲得唯一值時保持順序。 – Kaj 2011-06-07 08:43:31

+0

所以訂單保留在數組中。即如果沒有重複,則唯一的將與數組相同。 – 2011-06-07 08:43:36

2

你實際上並不需要的地圖。這是一個使用HashSet代替的示例。那些已經在(假設你想重複串「歸零」了出來。

String[] strs = "aa,bb,cc,aa,xx,cc,dd".split(","); 

Set<String> seen = new HashSet<String>(); 

for (int i = 0; i < strs.length; i++) 
    if (!seen.add(strs[i])) 
     strs[i] = null; 

// Prints [aa, bb, cc, null, xx, null, dd] 
System.out.println(Arrays.toString(strs)); 
+0

@Downvoter:留下評論? – aioobe 2011-06-07 08:43:44

1

你可以做到這一點在O(n)時間,通過遍歷您的陣列一次,每次新的元素扎進一個HashSet和更換數組元素該HashSetnulls

0

相反,你可以使用一組過一個HashMap的,步驟是(你可以工作的細節了自己):

  • 每一個字符串數組
  • 如果在地圖中存在串/設置爲null,
  • 否則它添加到地圖/集

就是這樣。

相關問題