算法性能技巧

算法性能提升总结

巧用hash表

利用hash,来进行映射,从而降低代码的复杂度,和冗余度

eg: 求两个数之和

class Solution:
    def twoSum(self, nums: List[int], target: int)->List[int]:
        """
        暴力方法实现时间复杂度为O(n*n)
        """
        n = len(nums)
        for i in range(n):
            for j in range(i  + 1, n):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []
    
    def two_sum(self, nums: List[int], target: int)->List[int]:
        """
        hash 表的实现,时间复杂度为O(n)
        """
        hash_table = dict()
        for i, num in enumerate(nums):
            if target - num in hash_table:
                return [hash_table[target - num, i]]
            hash_table.__setitem__(nums[i], i)
        
        return []

上述代码分析可知,使用hash表后,时间复杂度为O(n),相对于方法一,核心点在于怎么来优化找到target-num之后的索引
可以建立hash表,同时也可以利用python中list的内置函数index

posted @   酷酷的排球  阅读(67)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示