leetcode 1. Two Sum python
来源:互联网 发布:java底层源代码 编辑:程序博客网 时间:2024/06/06 00:00
闲的蛋疼,每天刷刷。可是发现自己第一题都不会啊,所以记录下来,方便自己复习。
题目
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.
给定一个整型的数组,和一个target。返回两个加起来的和为target的数字下标。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。并且每个元素只能使用一次。
例子
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解法
class Solution(object): def twoSum(self, nums, target): if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): print(buff_dict) if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = ia=Solution()print(a.twoSum(nums = [2, 7, 11, 15], target = 18))
解释
感觉解题的思想好奇妙。上面代码的运行结果如下所示:
{}{16: 0}{16: 0, 11: 1}[1, 2]建立一个buff_dict,这个dict的key为元素与target的差值,value为元素在nums列表中的下标。这样就保证了每个key-vaule对应的值之和为target。这样只要遍历nums列表,找到元素值等于dict中的key的值那个元素就好了。
所以通过 nums[i] in buff_dict 判断下,然后 return [buff_dict[nums[i]], i] 就ok了。
阅读全文
0 0
- 1.Two Sum Leetcode Python
- [Leetcode] 1.Two Sum @python
- LeetCode: 1. Two Sum python
- Leetcode: 1. Two Sum [python]
- [leetcode:python]1.Two Sum
- leetcode 1. Two Sum python
- 【Leetcode】【python】Two Sum, Two Sum II
- LEETCODE 1.Two Sum (python实现)
- Leetcode题解(Python): 1.Two Sum
- 【Leetcode】【Python】【C++】1. Two Sum实现
- LeetCode 1.Two Sum (Python)
- 【leetcode】1. Two Sum(Python & C++)
- LeetCode 1. Two Sum Python Solution
- leetcode two sum python 实现
- 【LeetCode with Python】 Two Sum
- LeetCode : No1 Two Sum Python
- [leetcode]-[Two Sum]-python实现
- [Leetcode.python] 001. Two Sum
- ORC图像识别
- 小白带你学安卓——UI设计
- 88. Merge Sorted Array
- php面试宝典7
- 三表联查 left join 写法
- leetcode 1. Two Sum python
- git fetch 的简单用法:更新远程代码到本地仓库
- [Android技术专题]不写单元测试活该你加班.md
- 安卓开发关于图片上传后出现旋转的问题
- Spring MVC入门须知
- Android源码分析-点击事件派发机制
- jdk源码学习笔记---Character
- 23 岁到 35 岁该如何实现资产增值?如何不陷入结婚生孩子买房的恶性循环中?
- 工作日记2017.07.13