Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
思路:使用排序和雙指針。
package leedcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 350. Intersection of Two Arrays II
*
* @author duola
*
*/
public class leetcode350 {
public static int[] intersect(int[] nums1, int[] nums2) {
List<Integer> res = new ArrayList<Integer>();
Arrays.sort(nums1);
Arrays.sort(nums2);
for (int i = 0, j = 0; i < nums1.length && j < nums2.length;) {
if (nums1[i] < nums2[j]) {
i++;
} else if (nums1[i] == nums2[j]) {
res.add(nums1[i]);
i++;
j++;
} else {
j++;
}
}
int[] out = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
out[i] = res.get(i);
}
return out;
}
public static void main(String[] args) {
int[] a = { 84, 5, 30, 84, 67, 78, 73, 38, 93, 92, 15, 43, 38, 81, 68,
65, 62, 21, 16, 38, 95, 68, 60, 35, 43, 95, 67 };
int[] b = { 82, 60, 70, 10, 94, 6, 44, 51, 1, 3, 97, 84, 3, 87, 91, 55,
81, 90, 45, 22, 18, 58, 62, 96, 27, 24, 16, 63, 30, 60, 29, 93,
27, 56, 79, 4, 69, 9, 21, 23, 7, 49, 62, 89, 22, 64, 85, 75,
55, 49, 57, 17, 84, 49, 8, 13, 94, 40, 75, 50, 93, 46, 36, 94,
50, 0, 3, 65, 49, 82, 45, 11, 53, 63, 27, 71, 45, 37, 45, 19,
21, 57, 66, 99, 94, 92, 44, 35, 84, 78, 80, 88 };
int[] c = intersect(a, b);
}
}