我是靠谱客的博主 大力小刺猬,这篇文章主要介绍Leetcode 1. Two SUM(两数之和)Python,现在分享给大家,希望可以做个参考。

  1. 方法一
    Class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
    n=len(nums)
    d={}
    for i in range(n):
    a = target - nums[i]
    if nums[i] in d:
    return d[nums[i]],i
    else:
    d[a]=i

  2. 方法二
    class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
    n=len(nums)
    for i in range(0,n):
    a = target - nums[i]
    if a in nums:
    j = nums.index(a)
    if i == j:
    continue
    else:
    return i,j
    break
    else:
    continue

  3. 方法三
    class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
    n=len(nums)
    for i in range(0,n):
    for j in range(i+1,n):
    if target-nums[i]==nums[j]:
    return i,j
    break
    else:
    continue

最后

以上就是大力小刺猬最近收集整理的关于Leetcode 1. Two SUM(两数之和)Python的全部内容,更多相关Leetcode内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(95)

评论列表共有 0 条评论

立即
投稿
返回
顶部