Algorithm to find intersection of two sets without using any data structure

前端 未结 3 874
时光取名叫无心
时光取名叫无心 2021-01-15 09:17

I would like to know the algorithm to determine the intersection of two arrays of equal elements (say, integer) without using any external data structure (like hash table) e

3条回答
  •  花落未央
    2021-01-15 09:39

    sort, then iterate using an iterator to each element array:

    if A[iter1] > B[iter2]: increase iter2
    else if A[iter1] < B[iter2]: increase iter1
    else: element is in intersection, print and increase both iters
    

    Sorting is O(nlogn), iterating is O(n), total O(nlogn)

提交回复
热议问题