알고리즘
[Swift 알고리즘] - Contains Duplicate (LeetCode)
Peppo
2023. 8. 8. 08:47
728x90
https://leetcode.com/problems/contains-duplicate/description/
주어진 배열에서 중복되는 요소가 있으면 `true`를 리턴, 없다면 `false`를 리턴
문제 사진
내 풀이
class Solution {
func containsDuplicate(_ nums: [Int]) -> Bool {
let numbers = Set(nums)
if nums.count != numbers.count {
return true
} else {
return false
}
}
}
Solution().containsDuplicate([1,2,3,1,3])
- 새로운 배열 numbers에 Set을 사용해서 중복되는 요소들을 걸러냄
- 주어진 배열과 numbers 배열의 길이(count)가 같지 않으면 중복된게 있다는 뜻이므로 true를 리턴하게 함. 아닐경우 false 리턴
다른사람의 풀이
배운것
Set()
정렬되지 않은 Collection으로 중복된 요소는 걸러냄
해시를 통해 값을 저장하기 때문에 검색속도가 빠른 장점이 있음.
예제
let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
if ingredients.contains("sugar") {
print("No thanks, too sweet.")
}
// Prints "No thanks, too sweet."
728x90