问题
I have this problem:
I want to iterate and compare each item of array1 against each item of array2, both arrays have the same lenght. When the value of both items coincide I store the value j in my indexOfInterest[] array for later use.
This is the code that I use, works well but its extremely slow comparing large arrays (thousands of items), can anyone help me in implement an efficient algorithm for this task.
int i,j;
int counter = [array1 count];
int indexOfInterest[counter];
for (i = 0; i < counter; i++) {
for (j = 0; j < counter; j++) {
if ([[array1 objectAtIndex:i] intValue] == [[array2 objectAtIndex:j]intValue] ) {
indexOfInterest[i] = j;
}
}
}
回答1:
You can store the indices of array1 in a hashmap (NSDictionary) where the keys are the elements/values and the value is the index of that element (or array of indices if elements are allowed to repeat). Call it map_of_array1.
Then iterate through array2 and find if map_of_array1[array2[[i]] is not null.
This way your time complexity will be O(n+m) instead of O(n*m).
来源:https://stackoverflow.com/questions/58475466/efficient-algorithm-for-comparing-and-iterate-through-two-large-arrays