我有一個字符串數組,我想查找數組中的重複字符串,並希望通過使用HashMap將重複項設置爲null一個好的時間複雜性。如何查找字符串數組的重複條目,並使用HashMap將它們設爲null
3
A
回答
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()]);
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
和更換數組元素該HashSet
與nulls
0
相反,你可以使用一組過一個HashMap的,步驟是(你可以工作的細節了自己):
- 每一個字符串數組 在
- 如果在地圖中存在串/設置爲null,
- 否則它添加到地圖/集
就是這樣。
相關問題
- 1. 查找.plist文件名並將它們作爲字符串放入數組中
- 2. 查找數組中的重複項,並使用javascript將它們刪除
- 3. 查找列表中的重複字符串,並使它們唯一
- 4. 如何使用Hashtable查找重複且唯一的字符串條目
- 5. 在2d字符串數組中查找重複的字符串
- 6. 查找數組中的重複條目
- 7. 如何比較HashMap的字符串並排列它們?
- 8. 檢查重複的字符串並丟棄它們?
- 9. 如何檢查目標C中的字符數組爲null null
- 10. 查找重複的值,並將它們添加到數
- 11. 在C++中查找字符串中的重複條目
- 12. 將字符串轉換爲符號並將它們轉換爲數組
- 13. 如何查找字符串數組中的所有非重複項目?
- 14. AngularJS - 在ID數組上重複,我該如何查找它們?
- 15. 查找並刪除所有重複的字符串,除非它們重複奇數次
- 16. 如何在MySQL中查詢重複的字符串條目
- 17. [Java]在沒有hashmap的情況下查找字符串中的重複字符並設置
- 18. 如何從字符串中除去數字,並將它們放入數組中?
- 19. 查找最長的重複字符串,並將其給定的字符串
- 20. 如何使用VBScript在主字符串中查找重複的子字符串
- 21. 無法初始化字符串數組,並使用它們
- 22. 如何檢索字典鍵/值,並將它們組合爲一個字符串
- 23. jQuery - 查找字符串並將字符串前置到它?
- 24. 查找字符串中的重複字符並確定它在python中重複的次數
- 25. 查找重複的字符數並計算它
- 26. 在文本文件中查找字符串並尋找它們
- 27. 如何在scala中將字符串數組轉換爲hashmap?
- 28. python查找字符串連接並用實際字符串替換它們
- 29. 如何搜索數組值並根據條件或字符串刪除它們?
- 30. C# - 添加值的字符串數組,除非它們是NULL
爲什麼「連接」?.. – aioobe 2011-06-07 08:41:14
@aioobe。在從集合中獲得唯一值時保持順序。 – Kaj 2011-06-07 08:43:31
所以訂單保留在數組中。即如果沒有重複,則唯一的將與數組相同。 – 2011-06-07 08:43:36