[LinkedIn]Intersection of two sorted array

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]);
        }
    }
}
posted on 2015-03-31 03:48  Seth_L  阅读(133)  评论(0编辑  收藏  举报