349. Intersection of Two Arrays

本文提供了一种解决LeetCode第349题两个数组的交集的方法,使用Kotlin编程语言实现。通过先排序再双指针遍历的方式,高效地找到两个数组中的共同元素,并确保结果中每个元素的唯一性。
/**
* 349. Intersection of Two Arrays
* https://leetcode.com/problems/intersection-of-two-arrays/description/

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]

Note:

Each element in the result must be unique.
The result can be in any order.
Kotlin version
* */
fun intersection(num1: IntArray, num2: IntArray): IntArray {
        num1.sort();
        num2.sort();
        var index1 = 0;
        var index2 = 0;
        var map = HashMap<Int, Int>();
        while (index1 < num1.size && index2 < num2.size) {
            if (num1[index1] < num2[index2])
                index1++;
            else if (num1[index1] > num2[index2])
                index2++;
            else {
                if (map.get(num2[index2]) == null)
                    map.put(num2[index2], num2[index2]);
                index1++;
                index2++;
            }
        }
        var totalIndex = 0;
        var result = IntArray(map.size);
        map.forEach { (key, value) ->
            result.set(totalIndex, key);
            totalIndex++;
        };
        return result;
    }

  

转载于:https://www.cnblogs.com/johnnyzhao/p/10264160.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值