Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class AlgorithmProblem{
- // Given two arrays (elements are sorted and distinct),
- // find the number of elements in common.
- public static void main(String[] args){
- int[] array1 = {1, 2, 3, 5, 8, 13, 21, 34, 55};
- int[] array2 = {2, 8, 10, 11, 12, 14, 15, 16, 17, 55};
- int result = commonElementCount(array1, array2);
- System.out.println(result);
- }
- private static int commonElementCount(int[] a, int[] b){
- if(a == null || b == null)
- throw new IllegalArgumentException();
- int i = 0;
- int j = 0;
- int common = 0;
- while(i < a.length && j < b.length){
- if(a[i] == b[j]){
- common++;
- i++;
- j++;
- } else if(a[i] > b[j]){
- j++;
- } else {
- i++;
- }
- }
- return common;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement