57.和为s的两个数字
Last updated
Last updated
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var temp: [Int : Int] = [:]
for num in nums {
guard target >= num else { break }
if let other = temp[num] {
return [num, other]
}
temp[target - num] = num
}
return []
}func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var l = 0, r = nums.count - 1
while l < r {
let a = nums[l], b = nums[r]
if a + b > target {
r -= 1
}
else if a + b < target {
l += 1
}
else {
return [a, b]
}
}
return []
}