zoukankan      html  css  js  c++  java
  • LeetCode 两数之和

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

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

    示例:

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

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


    思路:

    1. 最直接的思路,两层for循环,查找有没有加起来是target的两个数,测试过只超过32%的人,时间复杂度不够优秀,是N*N

    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:
                        return [i,j]

    2. 采用字典来记录数据,然后通过字典查找一次只需logN的复杂度,来实现最终N*logN的时间复杂度

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            nums_dict={}
            for i,num in enumerate(nums):
                nums_dict[i]=num
            for i in nums_dict:
                if (target - nums_dict[i]) in nums_dict.values():
                    if target - nums_dict[i] != nums_dict[i]:
                        for j in nums_dict:
                            if nums_dict[j] == target - nums_dict[i]:
                                return [i,j]
                    else:
                        for j in nums_dict:
                            if j == i:
                                continue
                            if nums_dict[j] == nums_dict[i]:
                                return [i,j]
  • 相关阅读:
    梅森素数
    高精度乘法
    快速幂取模
    高精度加法
    Linux 压缩&解压缩
    Lec_Cloud资源云平台
    IP102,IP102-K_V3.0 输入节点机
    A7互动主机
    音频处理器的使用
    关于测试随笔
  • 原文地址:https://www.cnblogs.com/gremount/p/9568512.html
Copyright © 2011-2022 走看看