LeetCode 1. Two Sum Python Solution
来源:互联网 发布:java线程池实现方式 编辑:程序博客网 时间:2024/06/07 00:52
此题目对应于 LeetCode 1
题目要求:
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.
给一个数组和一个数值,数组中有两个元素的和等于给定数值,求该两个元素在原数组中对应下标
这里我提供2个解法
解法1:粗暴解法,时间O(n^2),LeetCode运行时间 4945 ms
class Solution(object): def twoSum(self, nums, target): if len(nums)<2: return None if len(nums)==2: return [0,1] for i in range(len(nums)): left = nums[i] for j in range(i+1,len(nums)): right = nums[j] if left+right == target: return [i,j]
解法2:采取辅助的dict数据结构,只需进行一次遍历,时间O(n),LeetCode运行时间 35ms
值得注意的是判断某个key是否存在于dict中的时间复杂度是O(1)的,dict采用了hash的算法。
class Solution(object): def twoSum(self, nums, target): if len(nums)<2: return None if len(nums)==2: return [0,1] dic = {} for i in range(len(nums)): if nums[i] in dic: return [dic[nums[i]],i] else: dic[target-nums[i]] = i
参考文章
https://discuss.leetcode.com/topic/23004/here-is-a-python-solution-in-o-n-time
阅读全文
0 0
- LeetCode 1. Two Sum Python Solution
- [LeetCode] Two Sum, Solution
- [LeetCode 1] Two Sum solution
- 1.Two Sum Leetcode Python
- [Leetcode] 1.Two Sum @python
- LeetCode: 1. Two Sum python
- Leetcode: 1. Two Sum [python]
- [leetcode:python]1.Two Sum
- leetcode 1. Two Sum python
- LeetCode 1. Two Sum java solution with HashMap
- Lootcode 1. Two Sum The Solution of Python and Javas
- LeetCode #1 Two Sum C# Solution
- 【Leetcode】【python】Two Sum, Two Sum II
- LEETCODE 1.Two Sum (python实现)
- Leetcode题解(Python): 1.Two Sum
- 【Leetcode】【Python】【C++】1. Two Sum实现
- LeetCode 1.Two Sum (Python)
- 【leetcode】1. Two Sum(Python & C++)
- 学习编程第一天
- C数据结构-优化顺序队列
- 错误 You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work
- OSI七层模型详解物理层、数据链路层、网络层、传输层.....应用层协议
- 深度学习Deeplearning4j入门 实战(1):Deeplearning4j 手写体数字识别
- LeetCode 1. Two Sum Python Solution
- spring mvc 多文件上传
- Java远程调试(Remote Debug)方法
- Java数据结构与算法之数据结构-逻辑结构-集合(一)------集合类简析
- 亲身体验搭建apache2.4+php-5.6.28集成环境搭建(网上太多坑了。。。搭建2天搞定)
- js对<select><option>操作和jq的选择器
- C#语言中的Using语句块确保资源被释放
- c#页面展示两位小数
- Converting dual fisheye images into a spherical (equirectangular) projection