Skip to content

Instantly share code, notes, and snippets.

@connordavison
Last active October 13, 2015 15:25
Show Gist options
  • Save connordavison/49e41f4b52ba36509479 to your computer and use it in GitHub Desktop.
Save connordavison/49e41f4b52ba36509479 to your computer and use it in GitHub Desktop.
Count number of matching elements in two integer arrays
import java.util.Arrays;
class Solution {
public static int solve(int[] A, int[] B) {
int i = 0;
int j = 0;
Arrays.sort(A);
Arrays.sort(B);
int matches = 0;
while (i < A.length && j < B.length) {
if (A[i] == B[j]) {
matches++;
j++;
} else if (A[i] < B[j]) {
i++;
} else {
j++;
}
}
return matches;
}
public static void main(String[] args) {
int[] A = {1, 3, 9, 2};
int[] B = {1, 3, 20, 5, 2};
System.out.println("Starting");
// 3 should match
System.out.println(Solution.solve(A, B));
int[] C = {0, 6, 12, 18, 24, 30};
int[] D = {0, 12, 24, 36, 48, 60};
// 3 should match
System.out.println(Solution.solve(C, D));
int[] E = {1, 2, 3, 4, 5, 6, 7};
// 7 should match
System.out.println(Solution.solve(E, E));
int[] F = {-1, -2, -3, -4, -5, -6, -7};
// 0 should match
System.out.println(Solution.solve(E, F));
}
}
<?php
function solution($A, $B) {
$a_counts = $b_counts = array();
foreach ($A as $a) {
$a_counts[$a] = isset($a_counts[$a]) ? $a_counts[$a] + 1 : 1;
$b_counts[$a] = isset($b_counts[$a]) ? $b_counts[$a] : 0;
}
foreach ($B as $b) {
$a_counts[$b] = isset($a_counts[$b]) ? $a_counts[$b] : 0;
$b_counts[$b] = isset($b_counts[$b]) ? $b_counts[$b] + 1 : 1;
}
$duplicates = 0;
foreach ($a_counts as $k => $v) {
$duplicates += min($v, $b_counts[$k]);
}
return $duplicates;
}
function solution2($A, $B) {
$a_counts = array_count_values($A);
$b_counts = array_count_values($B);
$a_counts += array_fill_keys(array_keys($b_counts), 0);
$duplicates = 0;
foreach ($a_counts as $k => $v) {
$duplicates += isset($b_counts[$k]) ? min($v, $b_counts[$k]) : 0;
}
return $duplicates;
}
@connordavison
Copy link
Author

Output:

nasatyau@DANTE [~/Dropbox/codebox/java]$ java Solution
Starting
3
3
7
0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment