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

    Python两数之和

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

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

    思路一:

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            i = index_2 = None
            for i in range(0, len(nums)):
                if (target - nums[i]) in nums and ((target - nums[i]) != nums[i] or nums.count(nums[i]) > 1):
                    index_2 = nums.index(target - nums[i], i + 1)
                    break
    
            return [i, index_2] if index_2 else []
    

    思路二:

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            i = index_2 = None
            for i in range(0, len(nums)):
                if (target - nums[i]) in nums[i + 1:] and ((target - nums[i]) != nums[i] or nums.count(nums[i]) > 1):
                    index_2 = nums.index(target - nums[i], i + 1)
                    break
    
            return [i, index_2] if index_2 else []
    

    思路三:

    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            hash_map = {}
            for i, t in enumerate(nums):
                if target - t in hash_map:
                    return [hash_map[target - t], i]
                hash_map[t] = i
    
  • 相关阅读:
    stress-Linux系统压力测试工具使用及系统负载很高的几种场景测试
    execsnoop-短时进程追踪工具
    走迷宫--DFS
    马踏棋盘--dfs
    查询前缀出现的次数----字典树
    找两个质数和为偶数的两个数
    煤气灶---递归
    求合力
    hdu2089---不要62(数位DP)
    轻重匹配
  • 原文地址:https://www.cnblogs.com/zyyhxbs/p/12771769.html
Copyright © 2011-2022 走看看