leecode刷題(6)-- 兩個陣列的交集II
阿新 • • 發佈:2018-12-30
leecode刷題(6)-- 兩個陣列的交集II
兩個陣列的交集II
描述:
給定兩個陣列,編寫一個函式來計算它們的交集。
示例:
輸入: nums1 = [1,2,2,1], nums2 = [2,2]
輸出: [2,2]
說明:
- 輸出結果中每個元素出現的次數,應與元素在兩個陣列中出現的次數一致。
- 我們可以不考慮輸出結果的順序。
思路:
我們可以用遍歷窮舉的方法,但是時間複雜度肯定很高。不妨換個思路:先將陣列遞增排序,排序之後將兩個陣列同時遍歷(定義兩個陣列的指令碼變數,初始值為0,向後遍歷),比較同索引位置的元素是否相等,如果相等,則記錄下該值;如果不相等,將值較小的陣列的腳標加1,另一個數組的腳標等待。然後繼續遍歷比較,直到遍歷完短的陣列。
程式碼如下:
import java.util.Arrays; public class Intersect { public int[] intersect (int[] nums1, int[] nums2) { if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) { return new int[]{}; } Arrays.sort(nums1); Arrays.sort(nums2); int i = 0, j = 0, k = 0; int[] result = new int[Math.min(nums1.length, nums2.length)]; while (i < nums1.length && j < nums2.length) { if (nums1[i] == nums2[j]) { result[k++] = nums1[i]; i++; j++; continue; } else if (nums1[i] > nums2[j]) { j++; } else { i++; } } return Arrays.copyOf(result, k); //拷貝陣列 } public static void main(String[] args) { int[] nums1 = {1,2,2,1}; int[] nums2 = {2,2}; Intersect intersect = new Intersect(); int[] result = intersect.intersect(nums1, nums2); //Arrays.toString()方法將hash值轉為陣列 System.out.println(Arrays.toString(result)); } }