LeetCode*350. Intersection of Two Arrays II

LeetCode題目鏈接

注意:凡是以英文出現(xiàn)的,都是題目提供的,包括答案代碼里的前幾行。

題目:

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

解析:

這一題的思想也可以用來解決前面一題。首先對兩個數(shù)組排序,然后分別用兩個下標遍歷數(shù)組,找出相同的部分添加到result數(shù)組即可。
如果要解決前面一題,在最后一個else分支添加一句while (i < nums1.length && nums1[i] == nums2[j]) i++;

答案:(Java)

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int[] result = new int[nums2.length];
        int i = 0, j = 0, k = 0;
        while ( i < nums1.length && j < nums2.length) {
            if ( nums1[i] < nums2[j] ) {
                i++;
            }
            else if ( nums1[i] > nums2[j] ) {
                j++;
            }
            else {
                result[k++] = nums1[i++];
                // add to here
                j++;
            }
        }
        return Arrays.copyOfRange(result, 0, k);
    }
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容