167. Two Sum II - Input array is sorted

108 阅读1分钟

题目描述

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

解题思路

这个题目与第一题一样, 只不过是需要返回的数据不同, 我们同样可以使用暴力破解和map两种方法, 我们只来看一下map 的方法. 与第一题一样, 遍历的过程中查找/创建map, 当能在map中拿到值时, 当前遍历的index 和拿到的value就是结果. 注意: 要 +1
时间复杂度: O(n)

示例代码

func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
    var map: [Int: Int] = [:]
    for i in 0..<numbers.count {
        let num = numbers[i]
        if let temp = map[target - num] {
            return [temp+1, i+1]
        }else {
            map[num] = i
        }
    }
    return []
}