Two Sum_Leetcode
Posted Phinza
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Two Sum_Leetcode相关的知识,希望对你有一定的参考价值。
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
这题要求返回的是Index且nums并不是sort好的,诸如双指针等方法便无法很好的使用
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {} #1.创建一个空字典
for i in range(len(nums)):
if nums[i] in dic: #3.如果,当前值在dic(的keys里)里出现过,(找到2里所说的x了!)则其与记录的index对应的元素 合正好为target
return [dic[nums[i]], i]
else: #2.解题核心:将当前元素与目标相减,得出的差值以key的形式记录进字典里,其val为当前的index(解释为,需要与x相加才能合为target)
dic[target - nums[i]] = i
以上是关于Two Sum_Leetcode的主要内容,如果未能解决你的问题,请参考以下文章