Rozważmy dwa posortowane tablice: -
int[] array1 = {1,2,3,4,5,6,7,8};
int[] array2 = {2,4,8};
int i=0, j=0; //taken two pointers
Podczas gdy pętla będzie działać aż oba wskaźniki dotrzeć do odpowiednich długościach.
while(i<array1.length || j<array2.length){
if(array1[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++;
}
}
}
wyjściowe będą: -
2 4 8
Nie zamierzamy zrobić swoją pracę domową dla Ciebie – shoosh
To pytanie wywiad. – user288609
Czy to praca domowa teraz, a za 5 lat stanie się twoim kolegą, a ty to zrobisz, albo gorsze debugowanie to praca. – Guge