1. Two Sum

61 阅读1分钟

题目描述

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解题思路一

暴力破解法, 直接循环查看2个值的和是不是target
时间复杂度: O(n^2)

示例代码一

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    for i in 0..<nums.count  {
        for j in (i+1)..<nums.count {
            if (nums[i] + nums[j] == target) {
                return [i, j];
            }
        }
    }
    return [0, 0]
}

解题思路二

使用哈希map的特性, 记录之前遍历过的值
时间复杂度: O(n)

示例代码二:

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var tempDic = [Int: Int]()
    for (index, value) in nums.enumerated() {
        if let memberIndex = tempDic[target - value] {
            return [memberIndex, index]
        }
        tempDic[value] = index
    }
    return [0, 0]
}