想着用个双指针,左右两个往中间移动,发现时间上还是特别长。。
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var tempRight = nums.count - 1
var tempLeft = 0
var array = [Int]()
while tempLeft < tempRight {
if nums[tempRight] > target {
tempRight -= 1
continue
}
if nums[tempLeft] + nums[tempRight] == target {
array.append(nums[tempLeft])
array.append(nums[tempRight])
break
}
if nums[tempLeft] + nums[tempRight] > target {
tempRight -= 1
}
else
{
tempLeft += 1
}
}
return array
}
看了官方的算法。。 提交之后还不如上边的= = 困惑了
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var tempRight = nums.count - 1
var tempLeft = 0
var array = [Int]()
while tempLeft < tempRight {
let s = nums[tempLeft] + nums[tempRight]
if s > target {
tempRight -= 1
}
else if s < target
{
tempLeft += 1
}
else {
array.append(nums[tempLeft])
array.append(nums[tempRight])
break
}
}
return array
}
网友评论