swift5实现两数之和- leetcode

76 阅读1分钟

方法一

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 []
    }

方法二

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var collection = Dictionary<Int, Int>()
        for i in 0...nums.count {
            let anotherNum = target - nums[i]
            if collection[anotherNum] != nil {
                // print([nums[i], anotherNum])
                return [i, collection[anotherNum]!]
                }
                collection[nums[i]] = i
                }
                return []
    }