Intersection of Two Arrays
1. Title
349. Intersection of Two Arrays
2. Http address
https://leetcode.com/problems/intersection-of-two-arrays/
3. The question
Given two arrays, write a function to compute their intersection.
Example:
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.
4 My code(AC)
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { int [] empty = new int[0]; if( nums1 == null || nums2 == null) return empty; int len1 = nums1.length; int len2 = nums2.length; if( len1 <=0 || len2 <=0) return empty; int [] result = new int[Math.min(len1, len2)]; int [] re; int bf = Integer.MAX_VALUE; Arrays.sort(nums1); Arrays.sort(nums2); int i = 0, j = 0,curI = 0; while( i < len1 && j < len2) { if( nums1[i] == nums2[j]) { if( nums1[i] != bf) { result[curI++] = nums1[i]; bf = nums1[i]; } i++; j++; }else if( nums1[i] < nums2[j]){ i++; }else{ j++; } } re = new int[curI]; System.arraycopy(result, 0, re, 0, curI); return re; }}