Thursday, March 18, 2021

Common elements in two sorted arrays



import java.util.ArrayList;
import java.util.Arrays;

public class CommonNumbers {

	public static void main(String[] args) {
          int[] array1A = {1, 3, 4, 6, 7, 9};
          int[] array2A = {1, 2, 4, 5, 9, 10};
          Integer[] com = common(array1A,array2A);
          for(int i : com) {
              System.out.println(i);
          }

	}

	public static Integer[] common(int array1[], int array2[]) {
		
		int p1=0,p2=0;
		ArrayList<Integer> list = new ArrayList<>();
		while(p1<array1.length && p2 < array2.length) {
			
			if(array1[p1]  == array2[p2]) {
				list.add(array1[p1]);
				p1++;
				p2++;
			}else if(array1[p1] > array2[p2]) {
				p2++;
			}else {
				p1++;
			}
		}
		Integer[] common = new Integer[list.size()];
		return list.toArray(common);
	}
}

Output:-

1 4 9

No comments:

Post a Comment

How to sort an HashMap based on value

import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java....