栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【leetcode】1. 两数之和

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【leetcode】1. 两数之和

【leetcode】1. 两数之和
  • Python代码
    • 哈希查找
    • 暴力破解
  • 总结

Python代码 哈希查找
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap={}
        for index,num in enumerate(nums):
            another_num=target-num
            if another_num in hashmap:
                return [hashmap[another_num],index]
            hashmap[num]=index
        return None
暴力破解
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(len(nums)):
                if nums[i]+nums[j] == target and i != j :
                    return [i,j]
        return None
总结

1、使用字典便于查找和添加。哈希查找复杂度为O(1),相较于暴力破解效率更高。
2、题目关键在于,能否意识到将两数相减添加到字典中,便于以后查找的操作。

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1015586.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号