1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public int[] intersect(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2);
List<Integer> list = new ArrayList<>(); int index1 = 0, index2 = 0; while (index1 < nums1.length && index2 < nums2.length) { int num1 = nums1[index1]; int num2 = nums2[index2];
if (num1 < num2) { index1++; } else if (num1 > num2) { index2++; } else { list.add(num1);
index1++; index2++; } }
int[] array = new int[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } return array; } }
|
References
350. Intersection of Two Arrays II