349. Intersection of Two Arrays

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**<br> * 349. Intersection of Two Arrays<br> * https://leetcode.com/problems/intersection-of-two-arrays/description/<br><br>Example 1:<br><br>Input: nums1 = [1,2,2,1], nums2 = [2,2]<br>Output: [2]<br><br>Example 2:<br><br>Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]<br>Output: [9,4]<br><br>Note:<br><br>Each element in the result must be unique.<br>The result can be in any order.Kotlin version<br> * */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;
    }

  

posted @   johnny_zhao  阅读(93)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示