给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
写在Leetcode的题解
才发现Leetcode题解也支持markdown,感觉自己要转投怀抱了
结果
执行用时:28 ms, 在所有 Swift 提交中击败了100.00%的用户
内存消耗:13.9 MB, 在所有 Swift 提交中击败了57.41%的用户
思路
第一次,跟1. 两数之和 一样(就不从暴力方法开始了)
第二次,因为有升序条件,使用了双指针
看了下官方解答,思路是暴力到二分法 / 双指针
代码
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var numsDic: [Int: Int] = [:]
var low = 0, high = nums.count - 1
while low < high {
if nums[low] + nums[high] == target {
return [low + 1, high + 1]
} else if nums[low] + nums[high] > target {
high = high - 1
} else {
low = low + 1
}
}
print("Couldn't find two nums' sum equal to \(target)")
return []
}
}
网友评论