LeetCode Intersetion of two array

本文介绍了一种计算两个数组交集的算法实现,并提供了基于排序和基于HashMap两种解决方案。重点讲解了如何确保结果中元素的唯一性及正确处理重复元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

description:

Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.

解题思路: 使用排序算法然后再进行处理,注意当比较两个数组相等的时候,要排除相同的数据的情况,也就是一个选代表的过程,当两个数字是相等时也要注意同时将数组的下表加一。

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) {
            return null;
        }
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int[] arr = new int[Math.min(nums1.length, nums2.length)];
        int i = 0, j = 0, index = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] == nums2[j]) {
                if (index == 0 || arr[index - 1] != nums1[i]) {
                    arr[index++] = nums1[i];
                }
                j++;
                i++;
            } else if (nums1[i] > nums2[j]) {
                j++;
            } else {
                i++;
            }
        }
        int[] result = new int[index];
        for (int k = 0; k < index; k++) {
            result[k] = arr[k];
        }
        return result;
    }
}
当然,这道题目也能够使用hashmap的方式进行求解,当所要的数据存在于map中的时候,数组添加这个数,反复这一过程直到求解出所用的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值