LeetCode #1 Two Sum

LeetCode #1 Two Sum

Question

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].

Solution

Approach #1

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

Time complexity: O(n^2).

Space complexity: O(1).

Approach #2

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var map: [Int : Int] = [:]
        for (i, n) in nums.enumerated() {
            if let m = map[target - n] {
                return [m, i]
            }
            map[n] = i
        }
        fatalError("No solution")
    }
}

Time complexity: O(n).

Space complexity: O(n).

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6832633.html

posted on 2017-05-09 20:54  Silence_cnblogs  阅读(286)  评论(0编辑  收藏  举报