要求:
给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
优化前 时间复杂度O(n^2)
1 class Solution { 2 func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 3 var indexForNum : Int? 4 var indexForAnotherNum : Int? 5 6 for (index, value) in nums.enumerated() { 7 if nums.contains(target - value) { 8 9 indexForNum = index 10 indexForAnotherNum = nums.firstIndex(of: target - value)! 11 12 if indexForAnotherNum == indexForNum { 13 continue 14 } 15 break 16 } 17 } 18 return [indexForNum!,indexForAnotherNum!] 19 } 20 }
优化后
class Solution { func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var indexForNum : Int = 0 var indexForAnotherNum : Int = 0 var dictionary : [Int : Int] = [:] for (index, arrValue) in nums.enumerated() { if dictionary.values.contains(target - arrValue) { indexForAnotherNum = index for (key,dicValue) in dictionary { if dicValue == target - arrValue { indexForNum = key break } } break } dictionary.updateValue(arrValue, forKey: index) } return [indexForNum,indexForAnotherNum] } }