zoukankan      html  css  js  c++  java
  • 349. Intersection of Two Arrays

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

      

  • 相关阅读:
    HAOI2015 树上染色
    HAOI2010 软件安装
    T2 Func<in T1,out T2>(T1 arg)
    事无巨细
    LitJson JavaScriptSerializer
    数据库操作
    jQuery:总体掌握
    sql一个题的解法分析讲解
    Javascript系列:总体理解
    c#
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/10264160.html
Copyright © 2011-2022 走看看