두 가지 코드 작성
1. 브루트포스
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
for i in 0..<nums.count {
if let j = nums.lastIndex(of: target - nums[i]) {
if i != j {
return [i,j]
}
}
}
return []
}
for문 중첩 안하려고 해봐도..
결국은 for문과 똑같은 로직이고, 오래 걸림
2. 해시테이블 이용
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var hashTable = [Int:Int]()
for i in 0..<nums.count {
let diff = target - nums[i]
if hashTable[diff] != nil {
return [i, hashTable[diff]!]
}
hashTable[nums[i]] = i
}
return []
}
나름대로 만족
'알고리즘문풀 with SWIFT > LeetCode' 카테고리의 다른 글
swift ) Leetcode - 746. Min Cost Climbing Stairs (0) | 2024.02.16 |
---|---|
swift ) Leetcode - 771. Jewels and Stones (0) | 2022.11.27 |
swift ) Leetcode - 1880. Check if Word Equals Summation of Two Words. (0) | 2022.11.27 |
swift ) Leetcode 1662, 2418 (0) | 2022.11.27 |