1.暴力枚举
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var result = [Int]()
if nums.count < 2 {
return result
}
var p_1 = 0
while p_1 < nums.count {
for index in (p_1+1)..<nums.count {
if nums[p_1] + nums[index] == target {
result.append(p_1)
result.append(index)
return result
}
}
p_1+=1
}
return result
}
}
2.使用哈希表降低时间复杂度到O(n)
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var hashTable: [Int: Int] = [:]
for index in 0..<nums.count {
if hashTable[target - nums[index]] != nil {
return [hashTable[target - nums[index]]!, index]
}
hashTable[target - nums[index]] = index
}
return []
}
}