这几天看了Leetcode,准备有时间就刷刷,虽然很慢,但是能学到东西,首先我们看看问题描述:
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].
实现:swift
1.首先最容易想到的就是暴力解法,其实就是有点类似冒泡法,两个for循环分别遍历数组的每个元素,
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 []
}
当然可以解决问题,测试跑了一下400ms,但是我们仔细考虑一下,每个算法都有它的时间复杂度,i循环N次,j也要循环N次,那么时间复杂度应该为 O()
2.改进一下,使用hashmap,复杂度降为O(N)
func twoSumNew(_ nums:[Int],_ target:Int) -> [Int] {
var dict:[Int:Int] = [:]
var result:[Int] = []
for (i,n) in nums.enumerated() {
if let index = dict[target-n] {
result.append(index)
result.append(i)
break
}
dict[n] = i
}
return result
}
这个跑了一下36ms左右。
在object-C 和 swift 中,其字典就是一种典型的hash表结构,可以充分利用他这个结构快速查找,将数组的 value index反转 为字典相应的键值对,这样可以迅速的通过dict[value]查找是否存在相应的index而这个index就是之前数组的index。
这或许在今后的开发中对于我们数据的查找以及数据结构的选择方面能起到启发的作用...