zoukankan      html  css  js  c++  java
  • 算法两数之和 python版

    方法一、暴力解法 -- 5s
    复杂度分析:时间复杂度:O(n^2)空间复杂度:O(1)
    length = len(nums)
    for i in range(length):
        for j in range(i + 1, length):
            if nums[i] + nums[j] == target:
                return [i, j]
    方法二:利用python切片 - 1s
    复杂度分析:时间复杂度:O(n)空间复杂度:O(1)

    解题关键主要是想找到 num2 = target - num1,是否也在list中,其实原理跟2次遍历一样
    for i in range(len(nums)):
        if target-nums[i] in nums[i+1:]:
            return [i, nums.index(target-nums[i], i+1)]
    方法三:哈希 -- 80ms
    复杂度分析:时间复杂度:O(n)空间复杂度:O(n)

    直接哈希记录需要的key,遍历到就是找到需要的值:
    dic = {}
    for i, num in enumerate(nums):
        if num in dic:
            return [dic[num], i]
        else:
            dic[target - num] = i
    作者:aver58
    链接:https://leetcode-cn.com/problems/two-sum/solution/1liang-shu-zhi-he-by-aver58/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory
    pycocotools使用教程
    with torch.no_grad() 详解
    虚拟机Ubuntu上下载Pytorch显示超时
    Deep Layer Aggregation DLA网络的结构
    tgz文件解压命令
    install mysql at linux
    devops issue
    process data
    unittest
  • 原文地址:https://www.cnblogs.com/strawberry-1/p/11491663.html
Copyright © 2011-2022 走看看