Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
Given nums1 =
[1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
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 35 36 37 38 39 40 | public class Solution { public int [] intersection( int [] nums1, int [] nums2) { if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0 ) { return new int [ 0 ]; } Arrays.sort(nums1); Arrays.sort(nums2); int i = 0 ; int j = 0 ; List<Integer> result = new ArrayList<>(); while (i < nums1.length && j < nums2.length) { if (nums1[i] < nums2[j]) { i++; } else if (nums1[i] > nums2[j]) { j++; } else { if (result.isEmpty() || nums1[i] != result.get(result.size() - 1 )) { result.add(nums1[i]); } i++; j++; } } return listToArray(result); } private int [] listToArray(List<Integer> list) { int [] result = new int [list.size()]; for ( int i = 0 ; i < list.size(); i++) { result[i] = list.get(i); } return result; } } |
No comments:
Post a Comment