【Leetcode_Python & C語言】350. Intersection of Two Arrays II

提供兩個陣列,找出陣列中共同的元素,再以陣列的形式輸出。

題目在這:https://leetcode.com/problems/intersection-of-two-arrays-ii/

這題和上一題不同的是,只要是兩個陣列出現相同元素就需要以陣列的形式回傳,不需要判斷回傳的陣列中是否有重複的元素。

我們來看範例就一目了然了。

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

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?

Table of Contents

Python 解答1:

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        nums1.sort()
        nums2.sort()
        i = j = 0
        while (i < len(nums1) and j < len(nums2)):
            if nums1[i] > nums2[j]:
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                res.append(nums1[i])
                i += 1
                j += 1

        return res

C 語言:

int cmpFunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
        qsort(nums1, nums1Size, sizeof(int), cmpFunc);
        qsort(nums2, nums2Size, sizeof(int), cmpFunc);

        int *res;
        res=(int *)malloc(sizeof(int)*nums1Size);
        
        int i = 0;
        int j = 0;
        *returnSize=0;
        while (i < nums1Size && j < nums2Size){
            if (nums1[i] > nums2[j]){
                j ++;
            }else if (nums1[i] < nums2[j]){
                i ++;
            }else{
                res[(*returnSize)++]=nums1[i];
                i ++;
                j ++;
            }
                    
        }
            
        return res;
}

Leave a Comment

Your email address will not be published. Required fields are marked *