• 01 LeetCode---两数之和


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

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

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

    示例:

    1
    2
    3
    4
    给定 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)

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

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

  • 相关阅读:
    SPOJ913 Query on a tree II
    SPOJ375 Query on a tree
    HDU4348 To the moon
    Bzoj2753 [SCOI2012]滑雪与时间胶囊
    HDU4612 Warm up
    Uva11374 Airport Express
    Uva1624 Knots
    DevExpress的GridControl的使用以及怎样添加列和绑定数据源
    C#中使用Path、Directory、Split、Substring实现对文件路径和文件名的常用操作实例
    ZedGraph的曲线的LineItem对象的Tag属性存储信息进而在鼠标悬浮时进行显示
  • 原文地址:https://www.cnblogs.com/yanyufeng/p/9600681.html
Copyright © 2020-2023  润新知