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

      

  • 相关阅读:
    Android获取手机内存和sd卡相关信息
    总结(创建快捷方式等)
    正则是个好东西
    Android自定义AlertDialog
    Eclipse生成author等注释
    day18 io多路复用
    json 模块
    re 模块
    random 模块
    hashlib 模块
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/10264160.html
Copyright © 2011-2022 走看看