LC-349
阅读原文时间:2023年07月08日阅读:1

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Example 1:

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

Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output: [9,4]

Explanation: [4,9] is also accepted.

Constraints:

1 <= nums1.length, nums2.length <= 1000

0 <= nums1[i], nums2[i] <= 1000

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/intersection-of-two-arrays

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 单纯API去重

  • 排序 + 双指针

如果两个数组是有序的,则可以使用双指针的方法得到两个数组的交集。

首先对两个数组进行排序,然后使用两个指针遍历两个数组。

可以预见的是加入答案的数组的元素一定是递增的,为了保证加入元素的唯一性,我们需要额外记录变量 pre 表示上一次加入答案数组的元素。

初始时,两个指针分别指向两个数组的头部。

每次比较两个指针指向的两个数组中的数字,

如果两个数字不相等,则将指向较小数字的指针右移一位,如果两个数字相等,且该数字不等于 pre ,将该数字添加到答案并更新pre 变量,同时将两个指针都右移一位。

当至少有一个指针超出数组范围时,遍历结束。

Java实现

package LC.hash;

import java.util.HashSet;
import java.util.Set;

public class LC349 {
    public static void main(String[] args) {
        int[] nums1 = {1, 2, 2, 1};
        int[] nums2 = {2, 2};
        int[] res = intersection(nums1, nums2);
        for (int item :
                res) {
            System.out.println(item + ",");
        }
    }

    /**
     * API战士
     * @param nums1
     * @param nums2
     * @return
     */
    public static int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        //利用HashSet去重
        for (int i : nums1) {
            set1.add(i);
        }
        //set2 里面已经是交集
        for (int i : nums2) {
            if (set1.contains(i)) {
                set2.add(i);
            }
        }
        //最后return是 数组形式
        int[] arr = new int[set2.size()];
        int j = 0;
        for (int i : set2) {
            arr[j++] = i;
        }
        return arr;
    }
}

Python实现

from typing import List

class Solution:
    def intersection(self: List[int], nums2: List[int]) -> List[int]:
        self.sort()
        nums2.sort()
        length1, length2 = len(self), len(nums2)
        res = list()
        index1 = index2 = 0
        while index1 < length1 and index2 < length2:
            num1 = self[index1]
            num2 = nums2[index2]
            if num1 == num2:
                # 保证加入元素的唯一性
                if not res or num1 != res[-1]:
                    res.append(num1)
                index1 += 1
                index2 += 1
            elif num1 < num2:
                index1 += 1
            else:
                index2 += 1
        return res

int_nums1 = [1, 2, 2, 1]
int_nums2 = [2, 2]
print(Solution.intersection(int_nums2, int_nums2))

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章