[Leetcode.python] 001. Two Sum
来源:互联网 发布:人工智能网站 编辑:程序博客网 时间:2024/05/18 00:13
在学习新语言Python, 决定使用Python刷刷Leetcode.
- 题目001:Two Sum (https://leetcode.com/problems/two-sum/)
大意,给定一个数组nums和一个数target,确定有且只有一对坐标index1, index2, 使得nums[index1] + nums[index2] == target
- 解答:
- 最直接的方法,穷举 O(N^2),提交后会超时
def twoSum(self, nums, target): length = len(nums) answers = [] for index1 in range(0, length - 2): for index2 in range(index1 + 1, length - 1): if nums[index1] + nums[index2] == target: answers.append(index1 + 1) answers.append(index2 + 1) return answers
- 可以修改为先排序,时间复杂度O(N*logN)
def twoSum(self, nums, target): sorted_nums = sorted(nums, cmp=lambda x,y:cmp(x, y)) length = len(nums) index1 = 0 index2 = length - 1 while index1 < index2: gap = sorted_nums[index1] + sorted_nums[index2] - target if gap == 0: break elif gap < 0: index1 += 1 else: index2 -= 1 answers = [] for index in range(0, length): if (nums[index] == sorted_nums[index1]) or (nums[index] == sorted_nums[index2]): answers.append(index + 1) return answers
- 使用Hash/Set,可以进一步降低时间复杂度为O(N)
def twoSum(self, nums, target): num_set = set(nums) answers = [] # a. nums[index1] != nums[index2] for index1 in range(0, len(nums)): number_to_be_found = target - nums[index1] if number_to_be_found != nums[index1] and number_to_be_found in num_set: answers.append(index1 + 1) for index2 in range(index1 + 1, len(nums)): if nums[index2] == number_to_be_found: answers.append(index2 + 1) break break # b. nums[index1] == nums[index2] if answers == []: number_to_be_found = target / 2 if (number_to_be_found + number_to_be_found == target): for index in range(0, len(nums)): if nums[index] == number_to_be_found: answers.append(index + 1) return answers
- 注意事项
- 数组不确定为有序
- 可能存在重复的元素
欢迎大家关注我的微信公众号 - “水滴杂谈”
0 0
- [Leetcode.python] 001. Two Sum
- 【Leetcode】【python】Two Sum, Two Sum II
- leetcode two sum python 实现
- 【LeetCode with Python】 Two Sum
- 1.Two Sum Leetcode Python
- LeetCode : No1 Two Sum Python
- [leetcode]-[Two Sum]-python实现
- [Leetcode] 1.Two Sum @python
- leetcode-001-two sum-python
- Two Sum Leetcode Python Java
- LeetCode: 1. Two Sum python
- [LeetCode] Two Sum Python 题解
- Leetcode: 1. Two Sum [python]
- Python leetcode #1 Two Sum
- [leetcode:python]1.Two Sum
- leetcode 1. Two Sum python
- LeetCode 001. Two Sum
- 【LeetCode】001.Two Sum
- POJ3630(Trie树)
- hibernate查询介绍
- 手机管家中的黑名单功能
- H2数据库引擎
- EventBus 学习进阶
- [Leetcode.python] 001. Two Sum
- 比一比 WebService和WCF
- AsyncTask总结
- python文件操作与输入输出
- 学习《Python核心编程》做一下知识点提要,方便复习(一)
- Maven本地仓库配置
- 第十三周项目2-形状类族中的纯虚函数
- 题目1510:替换空格
- code兴趣,是最好的老师;灯塔