Leetcode 1 Two Sum
来源:互联网 发布:制作视频字幕软件 编辑:程序博客网 时间:2024/06/05 16:34
1. Two Sum
这个系列的博客是我在leetcode上做题时的一些心得,代码全部使用python。
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].
先上代码:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ result = {} for i, num in enumerate(nums): if target-num in result: return [result[target-num], i] else: result[num] = i
- 使用python内置函数enumerate同时取出索引和值
- result是一个辅助字典,key是具体的值,value是索引
- 计算target-num,看是否在result中存在,若存在则说明target-nums[i]=nums[index]成立,通过字典result找出另一个数字的index,返回index与i
- 若target-num的值不在字典中,将num作为key保存到字典中,value是num在nums中的索引
阅读全文
0 0
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- 循环队列
- synchronized和ReentrantLock的区别
- java 高并发程序设计-附录
- RDDs基本操作Transformation和action
- Matlab滤波器设计
- Leetcode 1 Two Sum
- Spring使用@Resource、@Autowired注入时出现空指针问题的原因
- 开始start
- 设置启动Eclipse的JDK版本
- Matlab运行ML课程作业
- dubbo和spring boot整合简约版(xml和annotation)
- Faster RCNN win版本
- 这是在遇到ftp用了多种方法均无法使用后找到的一种方法
- SpringMVC获取页面参数的五种方法