위의 주석처리는 전부 탐색하는 브루트 포스
밑에는 해쉬테이블 이용.
// class Solution {
// func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// let n = nums.count
// var an = [Int]()
// for i in 0..<(n-1){
// for j in i+1..<n{
// if nums[i] + nums[j] == target{
// return [i, j]
// }
// }
// }
// return []
// }
// }
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dict = [Int:Int]()
for i in 0..<nums.count{
let com = target - nums[i]
if dict.keys.contains(com) && dict[com] != i{
return [i,dict[com]!]
}
else{
dict[nums[i]] = i
}
}
return []
}
}
'리트코드 풀이' 카테고리의 다른 글
leetcode 1791. Find Center of Star Graph (파이썬) (0) | 2022.02.26 |
---|---|
leetcode 1342 number of steps to reduce a number to zero (swift) (0) | 2022.02.21 |
Leetcode 1313 풀이(파이썬, 스위프트) (0) | 2022.02.08 |
Leetcode 1528 풀이(파이썬, 스위프트) (0) | 2022.02.08 |
leetcode 1281 풀이(파이썬, 스위프트) (0) | 2022.02.07 |