[leetcode-1] Two sum
来源:互联网 发布:js array to json 编辑:程序博客网 时间:2024/06/05 03:35
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].
Hint:
首先建立hash,通过index遍历lst,如果target-lst[i] 在hash里面,返回hash[target-lst[i]], i,否则的话,继续往字典里面添东西,hash[lst[i]] = i。即这里的字典key是列表里面的数,value是列表的索引。
Code:
Class solution(object): def twoSum(self, nums, target): hash=dict() for i in range(len(nums)): if (target-nums[i]) in hash: return [hash[target-nums[i]], i] hash[nums[i]]=i return [-1, -1]
阅读全文
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
- mongoDB安全认证
- bzoj 2806 多个串匹配
- matlab find函数详解
- JavaScript-1-4:数据类型转换
- 将wierface标注转换为VOC格式
- [leetcode-1] Two sum
- Java基础部分第六节
- spring boot http调用其他服务并解析
- 利用git将网站上传到GitHub做静态服务器
- spring基本认识
- 单例模式
- 总结-2017/9/14
- 6-1 顺序表创建和就地逆置
- codevs3731 luogu2296 寻找道路