下一篇:LeetCode链表相加-Python<二>

 

题目:https://leetcode-cn.com/problems/two-sum/description/

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

 

解法一

求差值,判断差值是否在nums数组里

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """       
        n = len(nums)
        for x in range(n):
            b = target-nums[x]
            if b in nums:
                y = nums.index(b)
                if y!=x:
                    return x,y
                
       

时间复杂度:O(n2),空间复杂度:O(1)   (补充:python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n) 也就是 if b in nums 时间复杂度是O(n))

解法二

求差值、把差值存进字典里作为键、索引作为值,第一次循环理解:d[7]=0 即字典d={7:0},表示为索引0需要数组里值为7的元素配对。 if 判断是否为前面元素所需要配对的值 , 是则返回两个索引值。(补充:nums[x] in d  是判断值是否在字典某个key里面)

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """           
        n = len(nums)
        #创建一个空字典
        d = {}
        for x in range(n):
            a = target - nums[x]
            #字典d中存在nums[x]时
            if nums[x] in d:
                return d[nums[x]],x
            #否则往字典增加键/值对
            else:
                d[a] = x
        #边往字典增加键/值对,边与nums[x]进行对比
       

时间复杂度:O(1) 、空间复杂度O(n) (补充:dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1))

解法三

暴力循环、不多说

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """        
        #用len()方法取得nums列表的长度
        n = len(nums)
        #x取值从0一直到n(不包括n)
        for x in range(n):           
            #y取值从x+1一直到n(不包括n)
            #用x+1是减少不必要的循环,y的取值肯定是比x大        
            for y in range(x+1,n):
                #假如 target-nums[x]的某个值存在于nums中
                if nums[y] == target - nums[x]:
                    #返回x和y
                    return x,y                   
                

 时间复杂度:O(n2)、空间复杂度:O(1)

执行时间明显多于一和二。

 

性能:解法二>解法一>解法三 。(补充:不能根据这个图片的执行用时比较,应该从时间复杂度比较)

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!