Efficient Algorithm for comparing and iterate through two large arrays

让人想犯罪 __ 提交于 2021-01-29 07:54:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!