547 · Intersection of Two Arrays - LintCode
# Description
Given two arrays, write a function to compute their intersection.
- Each element in the result must be unique.
# Example
Example 1:
Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2],
Output: [2].
Example 2:
Input: nums1 = [1, 2], nums2 = [2],
Output: [2].
# code
public class Solution { | |
/** | |
* @param nums1: an integer array | |
* @param nums2: an integer array | |
* @return: an integer array | |
* we will sort your return value in output | |
*/ | |
public int[] intersection(int[] nums1, int[] nums2) { | |
if (nums1 == null || nums1.length == 0 || nums2== null || nums2.length == 0) { | |
return new int[]{}; | |
} | |
Arrays.sort(nums1); | |
Arrays.sort(nums2); | |
List<Integer> list = new ArrayList<>(); | |
int p1 = 0; | |
int p2 = 0; | |
while (p1 < nums1.length && p2 < nums2.length) { | |
if (nums1[p1] == nums2[p2]) { | |
if (list.size() == 0 || list.get(list.size() - 1) != nums1[p1]) { | |
list.add(nums1[p1]); | |
} | |
p1++; | |
p2++; | |
} else if (nums1[p1] < nums2[p2]) { | |
p1++; | |
} else { | |
p2++; | |
} | |
} | |
int[] res = new int[list.size()]; | |
for (int i = 0; i < list.size(); i++) { | |
res[i] = list.get(i); | |
} | |
return res; | |
} | |
} |