The intersection of two sorted arrays

后端 未结 8 1489
臣服心动
臣服心动 2020-11-29 02:21

Given two sorted arrays: A and B. The size of array A is La and the size of array B is Lb. How

8条回答
  •  不知归路
    2020-11-29 03:01

    Since this looks like a HW...I'll give you the algorithm:

    Let arr1,arr2 be the two sorted arrays of length La and Lb.
    Let i be index into the array arr1.
    Let j be index into the array arr2.
    Initialize i and j to 0.
    
    while(i < La and j < Lb) do
    
        if(arr1[i] == arr2[j]) { // found a common element.
            print arr[i] // print it.
            increment i // move on.
            increment j
        }
        else if(arr1[i] > arr2[j])
            increment j // don't change i, move j.
        else
            increment i // don't change j, move i.
    end while
    

提交回复
热议问题