LeetCode小白菜笔记[1]:Two Sum
LeetCode小白菜笔记[1]:Two Sum
1. Two Sum [Easy]
题目:
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].
就是给定一个数组,找到其中的两个值加起来给定特定值,并返回这两个数的indice。
首先,最简单的,考虑暴力的方法:
class Solution(object): def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""foundflag = 0for i in range(len(nums)-1):for j in range(i+1,len(nums)):if nums[i] + nums[j] == target :foundflag = 1return [i, j]if foundflag == 0:print('[*] : No Such Numbers')
结果。。。。
Runtime太久了。。。这是个O(n^2)的方法,虽然accepted了但是还是不能算解决了问题。
这告诉我们,暴力不可取。
下面考虑其他方法。由于我们的target给定,对于每一个确定的加数,另一个加数也确定了,因此实际上这是一个在数组中查找元素的问题。并且查找到元素后要返回其下标,所以indice应该时元素作为key对应的value。为了加快查找速度,采用HashTable的方法,以空间换取时间。在python中,dict 数据体即hash table的实现,其存取在数量较少,即没有哈希冲突的时候,都是 O(1) 的。因此先采用hash table把数组元素值作为要进行hash的key,其下标为value。此过程过一遍list,故O(n)。然后在过一遍list,每次都查一下target - nums[i] 在不在dict里,O(n) ,故时间复杂度O(n),但是空间复杂度也是O(n),相比于暴力的O(1)变多啦。
class Solution(object): def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""foundflag = 0hashtable = dict()for i in range(len(nums)):hashtable[nums[i]] = ifor j in range(len(nums)):if (hashtable.has_key(target-nums[j]) and not hashtable[target-nums[j]] == j):foundflag = 1return [hashtable[target-nums[j]], j]if foundflag == 0:print ('[*] : No Such Numbers')
这就好多啦,结果如下:
然后Solution里面还有更简单的方法,即 One-pass Hash Table,即在过list的过程中,对每一个数,先看hash table中有没有complement,如果有,直接输出,就不用继续计算啦,如果没有,就加到hash table里。这样只用过一边list即可,Complexity时间O(n),空间最多也是O(n)。
class Solution(object): def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""foundflag = 0hashtable = dict()for i in range(len(nums)):if (hashtable.has_key(target - nums[i])):foundflag = 1return [hashtable[target - nums[i]], i]else:hashtable[nums[i]] = iif foundflag == 0:print ('[*] : No Such Numbers')
结果:
- 总结
第一次做leetcode,自己还是naive。。。
三种方法:
Brute Force——- Time:O(n^2) ,Space:O(1)
Two-pass Hash——Time:O(n) ,Space:O(n)
One-pass Hash——Time:O(n) ,Space:O(n)
THE END
星期六, 09. 十二月 2017 06:10下午
LeetCode小白菜笔记[1]:Two Sum相关推荐
- LeetCode小白菜笔记[3]:Palindrome Number
LeetCode小白菜笔记[3]:Palindrome Number 9. Palindrome Number [Easy] 题目:Determine whether an integer is a ...
- LeetCode小白菜笔记[17]:Sqrt(x)
LeetCode小白菜笔记[17]:Sqrt(x) 69. Sqrt(x) [easy] Implement int sqrt(int x). Compute and return the squar ...
- LeetCode—494. 目标和(Target Sum)——分析及代码(Java)
LeetCode-494. 目标和[Target Sum]--分析及代码[Java] 一.题目 二.分析及代码 1. 动态规划 (1)思路 (2)代码 (3)结果 2. 动态规划+节省空间 (1)思路 ...
- 厉害了!LeetCode 解题笔记终于在GitHub开源了!
今天给大家分享2套手册.先看看一大牛整理了一套初学到进阶的 LeetCode学习资料,分享一个火爆 GitHub 的 LeetCode 刷题项目(Fucking Algorithm)最近终于出电子版了 ...
- Leetcode | Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...
- LeetCode 508. Most Frequent Subtree Sum
原题链接在这里:https://leetcode.com/problems/most-frequent-subtree-sum/description/ 题目: Given the root of a ...
- LeetCode 404. 左叶子之和(Sum of Left Leaves)
404. 左叶子之和 404. Sum of Left Leaves LeetCode404. Sum of Left Leaves 题目描述 计算给定二叉树的所有左叶子之和. 示例: 3/ \9 2 ...
- [Leetcode] Binary Tree Maximum Path Sum
这是LeetCode上的一道题目,需要求二叉树中两点路径的最大和.原题是 https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ ...
- leetcode 712. Minimum ASCII Delete Sum for Two Strings | 712. 两个字符串的最小ASCII删除和(暴力递归->傻缓存->DP)
题目 https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/ 题解 经典的 暴力递归 -> 傻缓存 -&g ...
最新文章
- 用stm32f10x建立新的工程重要步骤
- linux c rename 重命名文件和文件夹
- Easy UI Tree操作
- AQuery学习笔记(一)
- linux加载内核后如何运行app,Android app启动过程
- html的div显示到最左侧,HTML/CSS:如何淡化div的左右边缘?
- 使用mysql索引的规则
- python中print(chr(65))_Python语句print(chr(97))的运行结果是( )。_学小易找答案
- python入门基础知识实例-Python入门基础知识实例,值得收藏!
- python 图像识别_AI场景,3步懂图像识别产品
- qt写的在ok6410上的密码锁
- 2019年5月的Flag!
- 110kV终端变电站电气部分设计
- for循环次数太多的时间优化_matlab for循环过大程序运行慢解决方案
- 如何用机器学习算法计算特征重要性
- PS CS6视频剪辑基本技巧(一)CS6可以实现的视频剪辑功能
- Jetpack Compose
- 日期选择器,本月、上月、上季度、本季度、上半年、下半年、本年、上一年
- 关于GPS 转换实用地图算法
- 【MAC使用技巧】打不开xxx.pkg,因为它来自身份不明的开发者