Lootcode 1. Two Sum The Solution of Python and Javas
来源:互联网 发布:打破刚性兑付 知乎 编辑:程序博客网 时间:2024/06/08 09:56
Description:
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].
Python:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ table={}#创建字典 for index,n in enumerate(nums):#List中每一个元素的索引和值 a=target-n#计算当前值与target的差值 if a in table:#判断差值是否在字典中 return [table[a],index]#如果在,说明有前面的n值(差值)和现在的n值之和等于target,返回存有差值的table值 table[n]=index#如果不在,将当前索引存入字典{table[n]:index}
思路是创建一个字典,存入nums中每个值,值为key,索引为value,判断target与当前值的差值是否为已存入字典的值,如果有,则输出这两个值的索引。时间复杂度O(n)
Javascript:
/** * @param {number[]} nums * @param {number} target * @return {number[]} */var twoSum = function(nums, target) { let table={},a;/ for(let index=0;index<nums.length;index++) { a=target-nums[index]; if(a in table) { return [table[a],index]; } table[nums[index]]=index; }};
思路基本一致
0 0
- Lootcode 1. Two Sum The Solution of Python and Javas
- LeetCode 1. Two Sum Python Solution
- Leetcode 2. Add Two Numbers The Solution of Python and Javascript
- Leetcode 4. Median of Two Sorted Arrays The Solution of Python
- Leetcode 7. Median of Two Sorted Arrays The Solution of Python
- 1. Two Sum QuestionEditorial Solution My Submissions
- [LeetCode] Two Sum, Solution
- Leetcode 3. Longest Substring Without Repeating Characters The Solution of Python and Javascript
- "Sum of Two Integers" and "Sort Colors"
- 1. Two Sum (python)
- 1. Two Sum-python
- the sum of two fixed value
- The reversed sum of two reversed numbers
- [LeetCode 1] Two Sum solution
- Lintcode56 Two Sum solution 题解
- 371. Sum of Two Integers [easy] (Python)
- [leetcode: Python ]371. Sum of Two Integers
- A problem during the compilation of Lemur and the solution
- Android ViewPager + Fragment懒加载
- MATLAB第二次作业 例1.4-1~2
- 7层网络结构分析
- 人月神话--焦油坑
- socketpair理解
- Lootcode 1. Two Sum The Solution of Python and Javas
- python基础之函数
- shell小白 想玩自动化部署,无密码ssh 登录远程服务器,执行scp命令传送war包 并重启tomcat。
- rman恢复数据库二
- Ajax 传递数组问题
- 如何让Tomcat以Debug模式启动
- 31. Next Permutation
- C++Primer第五版 第十八章习题答案(11~20)
- CentOS 7 Vmware 安装后不能上网