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.
找出兩個無序數組中重合的值。面試
思路一模仿了歸併排序的merge部分。先將兩個數組分別排序,排序完成以後再用兩個指針分別比較兩個數組的值。若是兩個指針指向的值相同,則向結果集中添加該元素而且同時將兩個指針向前推動。不然指向的值較小的那個指針向前推動。算法
public int[] intersection(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2); List<Integer> nums3 = new ArrayList<Integer>(); int i=0, j=0; while(i<nums1.length && j<nums2.length){ if(nums1[i]==nums2[j]) { if(!nums3.contains(nums1[i])) nums3.add(nums1[i]); i++; j++; } else if(nums1[i]>nums2[j]) j++; else i++; } int[] arr = new int[nums3.size()]; for(int k=0;k<nums3.size();k++) arr[k]=nums3.get(k); return arr; }
受排序算法影響,該方法的時間複雜度爲O(nlgn)數組
一方面排序對時間的消耗很大,另外一方面數組中若是出現重複的值,也意味着大量無效的遍歷。那麼如何纔可以在不便利的狀況下獲取兩者的重合值。答案是爲其中一個數組經過創建索引的方式排序。
什麼叫創建索引的方式排序?這是指先獲取數組中的最大值max和最小值min,而後將整數數組轉化爲一個長度爲max-min+1的布爾型數組,布爾型數組i位置上的值表明原整數數組中是否存在數組i+min。如[1,6,7,0]
對應的布爾型數組爲[true,true,false,false,false,false,true,true]
。這其實是一種空間換時間的作法。經過這種方式,咱們就能夠在O(n)的時間複雜度內完成搜索。微信
public int[] intersection2(int[] nums1, int[] nums2){ if(nums1==null || nums2==null || nums1.length == 0 || nums2.length == 0){ return new int[0]; } int max = nums1[0], min = nums1[0]; for(int n : nums1){ if(n > max) max = n; else if(n < min) min = n; } boolean[] index = new boolean[max - min + 1]; for(int n : nums1){ index[n - min] = true; } int count = 0; int[] tmp = new int[Math.min(nums1.length, nums2.length)]; for(int n : nums2){ if(n>=min && n<=max && index[n-min]){ tmp[count++] = n; index[n-min] =false; } } return count == tmp.length ? tmp : Arrays.copyOf(tmp, count); }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~spa