The intersection of two sorted arrays

后端 未结 8 1483
臣服心动
臣服心动 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 02:54

    Let's consider two sorted arrays: -

    int[] array1 = {1,2,3,4,5,6,7,8};
    int[] array2 = {2,4,8};
    
    int i=0, j=0;    //taken two pointers
    

    While loop will run till both pointers reach up to the respective lengths.

    while(i array2[j])     //if first array element is bigger then increment 2nd pointer
           j++;
        else if(array1[i] < array2[j]) // same checking for second array element
          i++;
        else {                         //if both are equal then print them and increment both pointers
            System.out.print(a1[i]+ " ");
    
            if(i==a1.length-1 ||j==a2.length-1)   //one additional check for ArrayOutOfBoundsException
                break;
            else{
                i++;
                j++;
            }
        }
    }        
    

    Output will be: -

    2 4 8
    

提交回复
热议问题