Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
利用较小的数组建set 节省空间
1 public class Solution { 2 /** 3 * @param nums1 an integer array 4 * @param nums2 an integer array 5 * @return an integer array 6 */ 7 public int[] intersection(int[] nums1, int[] nums2) { 8 // Write your code here 9 if(nums1==null||nums2==null) return null; 10 if(nums1.length==0||nums2.length==0) return new int[0]; 11 12 Set<Integer> set = new HashSet<Integer>(); 13 List<Integer> res = new ArrayList<Integer>(); 14 15 int[] num1 = nums1.length>nums2.length?nums2: nums1; 16 int[] num2 = nums1.length<nums2.length?nums2: nums1; 17 18 for(int i: num1){ 19 set.add(i); 20 } 21 22 for(int i: num2){ 23 if(set.contains(i)){ 24 res.add(i); 25 set.remove(i); 26 } 27 if(set.size()==0) break; 28 } 29 int[] resInt = new int[res.size()]; 30 int index =0; 31 for(Integer i : res){ 32 resInt[index++]=i; 33 } 34 return resInt; 35 } 36 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步