[LeetCode/Kotlin]442. Find All Duplicates in an Array
2024. 2. 14. 11:48ㆍLeetCode/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
반응형
'LeetCode > Kotlin | Medium' 카테고리의 다른 글
[LeetCode/Kotlin]Medium - 34. Find First and Last Position of Element in Sorted Array (0) | 2024.05.09 |
---|---|
[LeetCode]Medium - 238. Product of Array Except Self (0) | 2024.03.21 |
[LeetCode/Kotlin]Medium - 6. Zigzag Conversation (0) | 2023.11.02 |
[LeetCode/Kotlin]Medium - 12. Integer to Roman (0) | 2023.11.02 |
[LeetCode/Kotlin]Medium - 396. Rotate Function (0) | 2023.10.13 |