Advertisement
zoltanvi

Two int arrays common element count

Jul 11th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.75 KB | None | 0 0
  1. public class AlgorithmProblem{
  2.  
  3.     // Given two arrays (elements are sorted and distinct),
  4.     // find the number of elements in common.
  5.  
  6.      public static void main(String[] args){
  7.         int[] array1 = {1, 2, 3, 5, 8, 13, 21, 34, 55};
  8.         int[] array2 = {2, 8, 10, 11, 12, 14, 15, 16, 17, 55};
  9.        
  10.         int result = commonElementCount(array1, array2);
  11.         System.out.println(result);
  12.     }
  13.    
  14.     private static int commonElementCount(int[] a, int[] b){
  15.         if(a == null || b == null)
  16.             throw new IllegalArgumentException();
  17.         int i = 0;
  18.         int j = 0;
  19.         int common = 0;
  20.        
  21.         while(i < a.length && j < b.length){
  22.             if(a[i] == b[j]){
  23.                 common++;
  24.                 i++;
  25.                 j++;
  26.             } else if(a[i] > b[j]){
  27.                 j++;
  28.             } else {
  29.                 i++;
  30.             }
  31.         }
  32.        
  33.         return common;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement