zoukankan      html  css  js  c++  java
  • (1)leetcode刷题Python笔记——两数之和

    题目如下:

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标

    你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素

    示例:

    给定 nums = [2, 7, 11, 15], target = 9
    
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    其他说明:

    题目说了不能重复利用数组中同样的元素,注意以下情况:

    nums = [3, 2, 4],target = 6,此时应该返回 [1, 2],而不是[0, 0]

    nums = [3, 3],target = 6,此时应该返回 [0, 1],而不是 [0, 0] 或 [1, 1]

    最简单的方法就是写两个 for 循环,找出相加等于 target 的那两个数

    但是为了不取到重复元素,第 2 个for循环要限制数组边界,从下一元素开始寻找,示意图如下

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            length = len(nums)
            for i in range(length):
                for j in range(i+1, length):
                    if (nums[i]+nums[j]==target):
                        return [i, j]

    两次 for 循环的效率不高,在评论区看到可以用字典来做,遍历元素的时候记录元素的下标

    当我们找 target-nums[i] 时候,只需要在字典找就可以了,查找字典时间复杂度为$O(1)$

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            n = len(nums)
            lookup = {}
            for i in range(n):
                tmp = target - nums[i]
                if tmp in lookup:
                    return [lookup[tmp], i]
                lookup[nums[i]] = i

    一种更清晰的方式

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            d={}
            for i,a in enumerate(nums):
                diff=target-a
                index=d.get(diff,-1)
                if index!=-1:
                    return [i,index]
                d[a]=i
  • 相关阅读:
    HDU 3572 Task Schedule(拆点+最大流dinic)
    POJ 1236 Network of Schools(Tarjan缩点)
    HDU 3605 Escape(状压+最大流)
    HDU 1166 敌兵布阵(分块)
    Leetcode 223 Rectangle Area
    Leetcode 219 Contains Duplicate II STL
    Leetcode 36 Valid Sudoku
    Leetcode 88 Merge Sorted Array STL
    Leetcode 160 Intersection of Two Linked Lists 单向链表
    Leetcode 111 Minimum Depth of Binary Tree 二叉树
  • 原文地址:https://www.cnblogs.com/dogecheng/p/11683670.html
Copyright © 2011-2022 走看看