力扣(leetcode)题库0001-python3

  试一下leetcode的题库,不知道对于我这种小白要多长时,但是目标已经种下,去做就是了。You can do anything you set your mind to.

题目:题库链接

中:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

英:Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you may not use the same element twice.

解答思路:

1. 两重for循环,遍历数组中所有的数。我就是这么做的,做完后感觉不是特别舒服,总感觉如果我自己是计算机的话,就恰似吃到了一道不是很美味的菜。

优:简单上手

缺:运行耗时

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

2. 哈希表,利用键值对来进行求解,第一个循环是更新过后了的字典,即无重复的键,第二个循环先得到所有的值与下标,然后拿target减去这个值,得到所需要的 j,再排除这个数是空值和它本身的可能,返回解

优:运算时间降低

缺:我太菜了,找不出来

def twoSum(nums,target):

  hashmap = {}

  for ind,num in enumrate(nums):

    hashmap[num] = ind

  for i, num in enumrate(nums):

    j = hashmap.get(target - num)

    if j is not None and i != j:

      return [i,j]

3.哈希表,利用键值对求解,相比上面的算法易懂一些,即从前向后进行循环时,先利用else操作,把前面的数先写进字典,再由后面的循环在d中找到target-nums[x](这个数是由之前的else操作写入

的)的时候,返回这两个下标。

优:运算时间降低

缺:我太菜了,找不出来

def twoSum(nums,target):

  d = {}

  n = len(nums)

  for x in range(n):

    if target - nums[x] in d:

      return d[target  - nums[x]], x

    else:

      d[nums[x]] = x

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
posted @ 2020-05-13 19:23  慎独兔  阅读(458)  评论(0)    收藏  举报