两数之和 two-Sum - Swift解法

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:
给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

题目地址:
https://leetcode-cn.com/problems/two-sum/description/

解法1: 暴力 时间复杂度O(n²)

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    for i in 0..

解法2 两次字典遍历.
时间复杂度O(n), 增加了点空间O(n)换时间.
参考了java的Hash, iOS的字典做法.
第一次遍历, 数组转字典, 数组中数字为key, 索引为value.
第二次遍历, 匹配返回.

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    
    var dict = [Int: Int]()
    for i in 0..

解法3 一次字典遍历法. 时间O(n), 空间O(n)
遍历过得i加到字典, 然后直到找到j再一起返回.

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var dict = [Int: Int]()
    for i in 0..

你可能感兴趣的:(两数之和 two-Sum - Swift解法)