349. Intersection of Two Arrays
Posted johnnyzhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; }
以上是关于349. Intersection of Two Arrays的主要内容,如果未能解决你的问题,请参考以下文章
349. Intersection of Two Arrays
349. Intersection of Two Arrays
Leetcode 349. Intersection of Two Arrays
[leetcode]349.Intersection of Two Arrays