給你兩個整數數組 nums1 和 nums2 ,請你以數組形式返回兩數組的交集。返回結果中每個元素出現的次數,應與元素在兩個數組中都出現的次數一致(如果出現次數不一致,則考慮取較小值)。可以不考慮輸出結果的順序。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
思路:排序+雙指針
class Solution {public int[] intersect(int[] nums1, int[] nums2) {int n = Math.min(nums1.length,nums2.length);int[] arr = new int[n];Arrays.sort(nums1);Arrays.sort(nums2);int i = 0;int j = 0;int k = 0;while(i<nums1.length&&j<nums2.length){if(nums1[i]==nums2[j]){arr[k] = nums1[i];k++;i++;j++;}else if(i<nums1.length&&j<nums2.length&&nums1[i]>nums2[j]){j++;}else{i++;}}return Arrays.copyOfRange(arr, 0, k);/* int[] res = new int[k];for(int p = 0;p<k;p++){res[p] = arr[p];}return res; */}
}
1.復制數組方法
Arrays.copyOfRange(int [] arr,int from,int to),arr為int型數組,from為開始角標值,to為終止角標值。(其中包括from角標,不包括to角標。即處于[from,to)狀態)