[LeetCode/Kotlin]442. Find All Duplicates in an Array

2024. 2. 14. 11:48LeetCode/Kotlin | Medium

728x90
반응형
 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 해석

배열 안에서 중복된 값만 뽑아내야 한다.

하지만 조건에 O(N)을 사용하라고 하였으므로 반복문은 한번만 돌아야 함.

그리고 추가 공간만 사용해야 한다는 사실을 명심하자 !!


풀이 방법

풀이 접근 과정

반복문을 한 번만 돌기 위해 map을 사용하여 중복된 값을 걸러내고자 하였다.

최종 소스코드

class Solution {
    fun findDuplicates(nums: IntArray): List<Int> {
        val map: HashMap<Int, Boolean> = hashMapOf()
        val answer = arrayListOf<Int>()

        nums.forEach {
            if (map[it] == null) {
                map[it] = true
            } else {
                answer.add(it)
            }
        }

        return answer
    }
}

map을 통해 중복된 값을 걸러내고,

걸러진 값은 바로 arrayList에 넣어 리턴시킨다.


Comment

비교적 쉽다고 느껴진 문제였다.

728x90
반응형