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 31 32 33 34
| class Solution { public int[] intersect(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2);
List<Integer> list = new ArrayList<>();
int i = 0, j = 0; int len1 = nums1.length, len2 = nums2.length; while (i < len1 && j < len2) { if (nums1[i] == nums2[j]) { list.add(nums1[i]); i++; j++; } else if (nums1[i] < nums2[j]) { i++; } else { j++; } }
int[] ans = new int[list.size()]; for (int k = 0; k < ans.length; k++) { ans[k] = list.get(k); } return ans; } }
|