Leetcode #1 2sum
来源:互联网 发布:idp诺思留学知乎 编辑:程序博客网 时间:2024/06/08 04:43
题目
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].
思路:取出一个数n,再从剩下的数中寻找target-n,使用一趟hash即可。
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ result = {} for idx, i in enumerate(nums): # 一定要是当前的index,防止[3,3] 返回[0,0]的情况 tmp = target - i if tmp in result: return [result[tmp], idx] result[i] = nums.index(i) return 'no solution'
这里只考虑一组解的情况,输出所有结果的如下:
待续
阅读全文
0 0
- Leetcode #1 2sum
- [Leetcode] #1#15#18 2Sum & 3Sum & 4Sum
- 【Leetcode】Combination sum 1,2
- Leetcode:2Sum,3Sum
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- leetcode 1|167.two sum 1|2 && 3.three sum && 16.3Sum Closest && 18. 4Sum
- leetcode--1、15、167 2Sum、3sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- [Leetcode] 2 Sum
- LeetCode|2Sum
- LeetCode:2Sum
- leetcode笔记:2Sum
- POP3收取邮件
- LightOJ-1282
- Download failed : Oracle JDK 7 is NOT installed
- 防止刷新或后退页面重复提交表单
- Android-Service学习总结
- Leetcode #1 2sum
- linux内存管理
- eclipse Dynamic Web Project工程报红叉
- Springmvc框架(非注解与注解)
- 我的CSDN博客开通啦
- android studio 快捷方式
- Python-17.11.06
- Dubbo+Zookeeper实现分布式服务和负载均衡
- LightOJ-1259