LeetCodeOJ Two Sum (python)
来源:互联网 发布:2017学生空间七天网络 编辑:程序博客网 时间:2024/05/17 09:01
题目:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be
less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
测试时给定给定输入为一个列表,求列表中两元素的和为目标的两值所在索引位置。
思路:先将列表中元素按值和索引位置存入字典中,在字典中索引目标,并返回所在位置。具体见代码:
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): l=len(num) result=[0,0] dict1={} if l<2: return tuple(result) else: for i,val in enumerate(num): dict1[val]=i for j in range(0,l): if (target-num[j]) in dict1 and j!=dict1[target-num[j]]: result[0]=min(j+1,dict1[target-num[j]]+1) result[1]=max(j+1,dict1[target-num[j]]+1) return tuple(result)
0 0
- LeetCodeOJ Two Sum (python)
- LeetcodeOJ Two Sum
- LeetCodeOJ:1Two Sum
- 【Leetcode】【python】Two Sum, Two Sum II
- LeetcodeOJ Add Two Numbers
- Two Sum(python)
- 1. Two Sum (python)
- 1. Two Sum-python
- 【LeetCodeOJ】Path Sum
- LeetCodeOJ 3sum
- LeetCodeOJ:2. Add Two Numbers
- leetcodeOJ 231. Power of Two
- leetcode two sum python 实现
- 【LeetCode with Python】 Two Sum
- 1.Two Sum Leetcode Python
- LeetCode : No1 Two Sum Python
- [leetcode]-[Two Sum]-python实现
- [Leetcode.python] 001. Two Sum
- JavaScript学习笔记(4)
- c函数之【字符串处理函数】
- OpenCV 实践程序1——图片显示及多图片融合
- 如何才能避免成为“工作狂”?
- c#完成的数制转换器---ShinePans
- LeetCodeOJ Two Sum (python)
- 经验分享:10个简单实用的 jQuery 代码片段
- 使用dbms_backup_restore包修改dbname及dbid
- github的常用命令/上传和下载代码
- php中检查服务器问题
- 模板 使用中注意的问题 template<class T>
- 父类子类静态块、游离块、构造方法的执行顺序
- CodeForces 8A Train and Peter (简单模拟题)
- MKNetworkKit简介