1. 两数之和

题目:

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

 

示例:

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

  因为 nums[0] + nums[1] = 2 + 7 = 9
  所以返回 [0, 1]

解法:

  • 最优解法

 1 class Solution:
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List(int)
 5         :type target: int
 6         :rtype List[int]
 7         """
 8 
 9         temp_dict = {}
10         for i, num in enumerate(nums):
11             if target - num in temp_dict:
12                 return [temp_dict[target - num], i]
13             
14             temp_dict[num] = i         # 不放在if语句前,为解决target-num=num的情况
View Code
  • 延伸知识点:

    1、判断key是否在dict中:
       key in c_dict

    2、带索引遍历:
       for i,value in enumerate(c_list)

    3、列表转字典
       c_dict = {}
        for i, value in enumerate(c_list):
            c_dict[i] = value

    4、字典推导式
        {value: key for key, value in c_dict.items()}

    5、查看某个元素element在list中的index
       c_list.index(element)

    6、通过pop移除并返回某个元素(通过指定index)
        c_list.pop()                        # 默认index=-1,即移除并返回最后1个元素
        c_list.pop(1)                       # 移除并返回第2个元素
View Code

 ★★★  如有问题,欢迎指正:raykindle@163.com  ★★★

原文地址:https://www.cnblogs.com/raykindle/p/12503667.html