티스토리 뷰
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
'알고리즘' 카테고리의 다른 글
[Swift 알고리즘] - Two Sum (LeetCode) (0) | 2023.08.17 |
---|---|
[Swift 알고리즘] - Valid Anagram (LeetCode) (0) | 2023.08.16 |
[Swift 알고리즘] - 영어가 싫어요 (Programmers) (0) | 2022.12.13 |
[Swift 알고리즘] - 7의 개수 (Programmers) (0) | 2022.11.23 |
[Swift 알고리즘] - 암호해독 (Programmers) (0) | 2022.11.17 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- Swift ModernRIBs
- RTCCameraVideoCapturer
- Swift 프로퍼티
- 2023년 회고
- Swift Leetcode
- swift protocol
- Class
- swift programmers
- ios
- swift (programmers)
- CS 네트워크
- swift reduce
- Combine: Asynchronous Programming with Swift
- Swift 프로그래머스
- removeLast()
- 원티드 프리온보딩
- RIBs tutorial
- Swift 내림차순
- iOS error
- Swift
- Swift joined()
- Swift inout
- Swift joined
- Swift RIBs
- swift property
- Swift 알고리즘
- Swift init
- Swift final
- swift 고차함수
- Swift Error Handling
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함