码迷,mamicode.com
首页 > 其他好文 > 详细

349. Intersection of Two Arrays

时间:2019-01-13 22:23:29      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:etc   fun   otl   leetcode   else   amp   inpu   key   http   

/**
* 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;
    }

  

349. Intersection of Two Arrays

标签:etc   fun   otl   leetcode   else   amp   inpu   key   http   

原文地址:https://www.cnblogs.com/johnnyzhao/p/10264160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!