본문 바로가기

알고리즘

릿코드 349. Intersection of Two Arrays 코틀린

두 배열중 겹치는거 반환해라
그냥 하나해시맵넣고 겹치면 resSet에 추가하면될듯

정답

class Solution {
    fun intersection(nums1: IntArray, nums2: IntArray): IntArray {
        val num2Map = hashMapOf<Int, Int>()
        for (i in nums2){
            num2Map[i]=num2Map[i]?.plus(1)?:1
        }
        val sortNum1List = nums1.sorted()
        val resSet= mutableSetOf<Int>()
        for (i in sortNum1List){
            if (num2Map[i]!=null){
                resSet.add(i)
            }
        }
        return resSet.toIntArray()
    }
}