Skip to content
16 changes: 16 additions & 0 deletions contains-duplicate/delight010.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution {
func containsDuplicate(_ nums: [Int]) -> Bool {
var dictionary: [Int: Int] = [:]
for (index, num) in nums.enumerated() {
// 배열 nums의 개수만큼 반복합니다. 시간복잡도 O(n)
if let value = dictionary[num], value != index {
return true
// 만일 동일한 숫자를 일찍 찾게 된다면
// 시간복잡도는 O(n)보다 더 빨라질 수 있습니다.
}
dictionary[num] = index
}
return false
}
}

15 changes: 15 additions & 0 deletions house-robber/delight010.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Solution {
func rob(_ nums: [Int]) -> Int {
var sum1 = 0
var sum2 = 0
for num in nums {
// for문을 통해 루프.
// 시간복잡도는 O(n)
let temp = max(num + sum1, sum2)
sum1 = sum2
sum2 = temp
}
return sum2
}
}

26 changes: 26 additions & 0 deletions longest-consecutive-sequence/delight010.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution {
func longestConsecutive(_ nums: [Int]) -> Int {
if nums.isEmpty { return 0 }
// .isEmpty 메서드를 사용하여 배열의 개수가 0일 시 바로 0을 리턴합니다.
// 시간복잡도 O(1)
var maxCount = 0
var count = 1
var prefixNumber = nums.sorted().first ?? 0
for num in nums.sorted(by: <) {
// nums 배열을 오름차순 정리 후 반복문을 루프합니다.
// .sorted 시간복잡도 O(n log n)
// for문 시간복잡도 O(n)
if prefixNumber == num {
continue
} else if prefixNumber + 1 == num {
count += 1
prefixNumber = num
} else {
maxCount = max(maxCount, count)
count = 1
prefixNumber = num
}
}
return max(maxCount, count)
}
}
19 changes: 19 additions & 0 deletions top-k-frequent-elements/delight010.swift
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dictionary를 이용하여 간단하고 직관적으로 문제 풀이를 하여 저도 많은 참고가 되었습니다~!

Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
var dictionary: [Int: Int] = [:]
for num in nums { // for loop를 돌면서 O(n)의 시간복잡도
dictionary[num, default: 0] += 1
// Swift에서 dictionary 검색의 시간복잡도는 O(1)
}

return dictionary
.sorted(by: { $0.value > $1.value })
// dictionary sorted()의 시간복잡도 O(n log n)
.prefix(k)
// k의 개수만큼 탐색합니다. 고로 시간복잡도는 O(n)
.map(\.key)
// prefix에서 k만큼 탐색하였습니다.
// .map의 시간복잡도는 O(n)입니다.
}
}

15 changes: 15 additions & 0 deletions two-sum/delight010.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dictionary: [Int: Int] = [:]
for (index, value) in nums.enumerated() {
// nums배열의 개수만큼 반복합니다. O(n)
let difference = target - value
if let otherIndex = dictionary[difference] {
return [otherIndex, index]
}
dictionary[value] = index
}
return []
}
}