[英]How to find duplicates in a linkedlist - java
您將如何瀏覽鏈表以找到列表中的第一個重復對象,可以使用嵌套的for循環(如數組)來完成它嗎?
創建一個新的HashMap。 迭代您的列表,並將列表中的對象添加到將其映射到Boolean.TRUE的HashMap中。 在將對象添加到HashMap之前,請檢查該對象是否已在HashMap中。 如果已經存在-這是第一個重復項。
您還可以將元素添加到HashSet中,直到遇到第一個重復項:
Set<YourObject> set = new HashSet<YourObject>();
for (YourObject obj : yourList) {
if (!set.add(obj)) { // check if already existed in the set
return obj; // found the duplicate
}
}
應該比嵌套循環更有效;)
您可以檢查列表中對象的第一個和最后一個索引。 如果兩者的減法都小於0,則意味着您有一個重復項。
LinkedList<String> s = new LinkedList<>();
/*
* Fill it here
*/
for(String str : s){
if(linkedList.indexOf(str) - linkedList.lastIndexOf(str) < 0){
System.out.println("First duplicate is: " + str);
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.