1.Two Sum (Easy)
时间复杂度对O(n^2)
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
for i in 0 ..< nums.count {
for j in i + 1 ..< nums.count {
let result = nums[i] + nums[j]
if result == target {
return [i, j]
}
}
}
return [-1, -1]
}
时间复杂度O(n)
func twoSum_3(_ nums: [Int], _ target: Int) -> [Int] {
var numberIndexDict = [Int:Int]()
for (index, num) in nums.enumerated() {
guard let pairedIndex = numberIndexDict[target - num] else {
numberIndexDict[num] = index
continue
}
return [pairedIndex, index]
}
return [-1, -1]
}