Leetcode: 1. Two Sum [python]
来源:互联网 发布:淘宝卖家可以不发货吗 编辑:程序博客网 时间:2024/05/17 22:44
- Two Sum
地址:https://leetcode.com/problems/two-sum/#/description
Python
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ return_list = [] #dict = {} for i in range(0,len(nums)): #list = [] for j in range(i+1,len(nums)): #print i,j temp = nums[i]+nums[j] if temp == target: return [i,j] #print return_list #return return_list
用了双循环,时间复杂度肯定是O(n^2)还是比较复杂的,看看别人的参考a Python solution in O(n) time:
https://leetcode.com/problems/two-sum/#/solutions
class Solution(object): def twoSum(self, nums, target): if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = i
每遍历一个数,把target减去该数的值存入buff_dict中,如果在接下来的数中有,直接返回两数index
0 0
- 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】【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++)
- LeetCode 1. Two Sum Python Solution
- leetcode two sum python 实现
- 【LeetCode with Python】 Two Sum
- LeetCode : No1 Two Sum Python
- [leetcode]-[Two Sum]-python实现
- [Leetcode.python] 001. Two Sum
- 视频相关App总贴记录
- 名企笔试题-棋子翻转、平均年龄、钓鱼比赛、最高分是多少
- 使用c3p0连接数据库的几种方式
- shell脚本for循环知识
- Android 5.X与Android4.X版本机器人动画的区别以及制作动画的方法
- Leetcode: 1. Two Sum [python]
- 初识Spring Boot
- GreenDao初体验
- servlet+ajax智能搜索框智能提示
- IOS使用UICollectionView完成列表功能
- 计蒜客 字符串长度
- Java正步走——学习Java之前的思考
- 行为型模式总结
- java基础总结12-面向对象8(Object类)