【LeetCode】1.Two Sum 两数之和

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解题思路1:

两个循环,轻松搞定:

for i in range(len(nums)):
    for j in range(i + 1, len(nums)):
         if nums[i] + nums[j] == target:
             return [i, j]

然则- -LeetCode竟然说超时....想想也是,这个时间复杂度为n²,确实可以优化。

解题思路2:

在一次遍历之中,就可以浏览所有的数,不需要第二次遍历。只需要在一次遍历中,判断第二个数是否存在即可。

i = 0
while True:
    num = nums[0]
    sect = target - num
    nums.remove(num)
    i = i + 1
    if sect in nums:
        return i - 1, nums.index(sect) + i

然则- -LeetCode说用了1424 ms,只打败了22.57%的其他Python3用户。
这个的时间复杂度为2n,很难优化

解题思路3:

我读了下官方示例Java代码,发现,它与我思路相似,时间复杂度也是2n,但是,它是从小往大找,而我是从大往小找,把时间复杂度画成图大致是这样:

在极限情况下,我们使用的时间一致,但其他情况下我都远不如它。
改代码后大致是这样:

list = []
for num in nums:
    otherNum = target - num
    if otherNum in list:
        first = nums.index(otherNum)
        nums.remove(otherNum)
        return [first, nums.index(num) + 1]
    list.append(num)

代价是空间复杂度上多了个数组。但我们假设空间无限大,只看时间复杂度。
但实际上,此增加空间复杂度而换来的时间,划算。
然则,LeetCode说用了560 ms,只打败了30.92%的其他Python3用户。

解题思路4:

官方示例Java代码中,使用的是Map,不是List。
我们也换成Map试下:

dict = {}
lenth = len(nums)
for i in range(lenth):
    otherNum = target - nums[i]
    if otherNum in dict:
        return [dict[otherNum], i]
    dict[nums[i]] = i

36 ms,只打败了99.68%的其他Python3用户。
可恶!字典比列表强这么多么!
反而言之,字典的空间复杂度比列表的空间复杂度高多少呢?性价比如何?
应该要读数据结构书吧.....


是否有更优秀的算法呢?
我不知道..
我还是没读到算法书..也没找到LeetCode查看更优秀的代码的方法。

猜你喜欢

转载自blog.csdn.net/tiantuanzi/article/details/83752436
今日推荐