Leetcode 1. 两数之和

题目描述

  给定整数数组 和目标值,在数组中找到和为目标值的两个整数,并返回他们的下标。示例:

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

  nums[0] + nums[1] = 2 + 7 = 9
   返回 [0, 1]

解决方法

1.  双重for循环: (运行时间60ms)

class Solution:
    def twoSum(self,nums, target):
        n = len(nums)
        for i in range(n):
            for j in range(i+1,n):
                if nums[i] + nums[j] == target:
                    return i, j

2. 单层for循环

使用index代替内循环得到索引值

class Solution:
    def twoSum(self,nums, target):
        n = len(nums)
        for i in range(n):
      a = target - nums[i]
      if a in nums:
        j = nums.index(a)
        if i != j:
          return i, j

3. 使用dict (运行时间:40ms)

建立dict,存入元素a并查找数组中当前元素是否在字典中

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 
posted @ 2020-05-03 18:53  如鹿~  阅读(132)  评论(0编辑  收藏  举报