[LinkedIn]Intersection of two sorted array

来源:互联网 发布:美图秀秀mac官方 编辑:程序博客网 时间:2024/06/11 02:27

print intersection of two sorted array
思路from g4g:
1) Use two index variables i and j, initial values i = 0, j = 0
2) If arr1[i] is smaller than arr2[j] then increment i.
3) If arr1[i] is greater than arr2[j] then increment j.
4) If both are same then print any of them and increment both i and j.

void intersection(int[] a, int[] b) {    if(a.length == 0 || b.length == 0) {        return 0;    }    int i = 0, j = 0;    while(i <= a.length && j <= b.length) {        if(a[i] < b[j]) {            i++;        } else if(a[i] > b[j]) {            j++;        } else {            System.out.println(a[i]);        }    }}
0 0