Write a program to find common integers between two sorted arrays. Both arrays are sorted in ASC order. Both arrays doesn’t have any duplicate numbers. Make sure you navigate through both arrays only once.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.java2novice.algos; public class CommonElementsInArr { public static void main(String a[]) { int[] input1 = {2,7,17,19,20,45,56,159,239}; int[] intput2 = {7,12,15,19,22,34,55,150,159}; int index1 = 0; int index2 = 0; while(true) { if(index1 >= input1.length || index2 >= intput2.length) { break; } if(input1[index1] == intput2[index2]) { System.out.print(input1[index1]); System.out.print(" "); index1 += 1; } else if(input1[index1] < intput2[index2]) { index1 += 1; } else { index2 += 1; } } } } |
Output:
1 2 3 |
7 19 159 |