我是靠谱客的博主 长情大雁,最近开发中收集的这篇文章主要介绍LeetCode刷题之——两数之和(Python解答),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  写在开头的话:印象中读研之后就好久没有更新博客,本科用来记录代码练习的方式不能荒废,从今天开始由易到难刷LeetCode上的算法题,主要使用Python3来解决,以发博客的形式记录,也作为学习的笔记与心得,希望自己能够坚持下去,也以此方式让学习看得见!也欢迎大家交流与讨论!

解答:

(1)本人采取的暴力解答法,即采取两个循环,遍历整个LIST,代码如下:

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(i+1, len(nums)):

                if nums[i] + nums[j] == target:

                    result = [i , j]

                    return result

提交结果如下:

采用暴力方法虽然提交通过,但是时间复杂度较高,所以在python语言解决问题的基础上寻求更好的解决办法。

(2)由于使用python这一集成度较高的高及编程语言,故采用其特有的字典形式来模拟哈查询的国车过,达到降低复杂度的效果,代码如下:

class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        hashmap = {}

        for index, value in enumerate(nums):

            hashmap[value] = index

        for index, value in enumerate(nums):

            j = hashmap.get(target - value)

            if j is not None and index!=j:

                return [index, j]

运行结果如下:

(3)对第二种方法提出改进,只寻找当前value值与target之差的值是否在当前value值之前即可,代码如下:

class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        hashmap = {}

        for index, value in enumerate(nums):

            if hashmap.get(target - value) is not None:

                return [index, hashmap.get(target - value)]

            hashmap[value] = index

提交结果如下:

可以看出,用字典模拟哈希表的方式来进行寻找两数之和更加地快速,运行效率更高。

 

 

 

 

 

 

 

 

最后

以上就是长情大雁为你收集整理的LeetCode刷题之——两数之和(Python解答)的全部内容,希望文章能够帮你解决LeetCode刷题之——两数之和(Python解答)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部