Search in ArrayList
I have 2 ArrayLists that have a Array of Strings as a "开发者_StackOverflowcomponent". I want to find the "components" whose first element is the same in both ArrayLists. To be more clear:
ArrayList One
first component => {"0", "zero"}
second component => {"1", "one"}
ArrayList Two
first component => {"1", "uno"}
second component => {"2", "two"}
I would like to loop through ArrayList Two and find {"1","uno"}. So far I have a nested loop that loops through the first array and then checks the current component to each component in ArrayList Two.
for(int i=0; i<One.size(); i++)
{
for(int j=0; j<Two.size(); j++)
{
if( fileOne.get(i)[0].equals( Two.get(j)[0] ) )
{
System.out.print( Two.get(j)[0]+" " );
System.out.print( Two.get(j)[1] );
System.out.println();
}
}
}
I think there should be a better solution. Any help
Use a HashSet.
Set<String> set = new HashSet<String>()
for(int i=0; i<One.size(); i++) {
set.add(fileOne.get(i)[0]);
}
for(int i=0; i<Two.size(); i++) {
String component[] = Two.get(j)
if(set.contains(component[0])) {
System.out.print( component[0]+" " );
System.out.print( component[1] );
System.out.println();
}
}
Note: A List would not work in this case, because lookups in Lists are O(N). Lookups in HashSets are O(1), so building the set (first loop) is O(N). Then going through your second array is O(M) and each lookup is O(1).
Overall, this becomes O(N) + ( O(M) * O(1) ) = O(N+M)
Edit: for Ted's comments.
You might try a hashmap. Initialize it from the first ArrayList by mapping the first element of each component to the component (or the index of the component). Then for each component of the second ArrayList, you can look up by the first element of each component to find the matching component (or discover that there isn't one when it returns null
).
Use two hashsets and the method retainAll such that:
One.retainAll(Two)
Complexity wise is better - only O(n+m) against your O(n*m). And in terms of readability and maintainability is also better. Notice that retainAll
will modify the hashset One
if you don't want behavior make a third copy.
(edited in response to Ted's comment)
Without initialization work such as sorting/hashing, or maintaining a sorted/hashed list, there is no better solution, an optimal solution is O(n*m) which yours is. That's the optimal solution because you have to compare every element to every other element.
I should also mention that in certain scenarios, it may be wiser to keep the list sorted. Then instead of comparing every element you could use a binary search or something. But without sorting your list first, yes you have to compare all elements. I believe the best possible sorting time is O(nlgn). Then after that sort process you'd still have to search the sorted list for your element, but searching a sorted list can be faster than searching an unsorted one.
精彩评论