leetcode01 Two Sum 寻找列表中和为定值的元素位置
来源:互联网 发布:java基础代码 编辑:程序博客网 时间:2024/06/07 04:57
刷刷leetcode。
problem 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].我的解法(很蠢):
# my solutionclass Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): for j in range(i+1,len(nums)): while nums[i] + nums[j] == target: return i,jsol = Solution()sol.twoSum([3,2,4],6)别人的优质解法,复杂度为O(n)
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 print buff_dictsol = Solution()sol.twoSum([3,2,6,5],7)
解读一下别人的优质解法:
新建空字典buff_dict,将前面出现过的目标值-数字作为key,数字的位置作为value存入buff_dict,打个比方列表是[2,4,5,3],定值是7。我们从位置0开始,先存入{7-2:0},再存入{7-4:1},所以buff_dict现在是{5:0,3:1},只要后面出现5或者3,就说明我们找到了元素和为8的两个元素。
总结:生成一个以目标值减去前面出现的元素为key,出现的元素位置为value的字典。这样我们就知道,前面的元素需要这些值就可以满足和为定值的条件了,后面只要出现一个,就直接把value和当前值的位置作为结果返回。
阅读全文
0 0
- leetcode01 Two Sum 寻找列表中和为定值的元素位置
- 寻找树中和为定值的所有路径
- 1048. Find Coins (25) -- 二分法,寻找和为定值的两个数 (Two Sum - leetcode)
- LeetCode01-two sum
- LeetCode01:Two Sum
- LeetCode01 Two Sum
- 【July第4题】寻找二叉树中和为某一定值的路径
- 寻找和为定值的组合
- 寻找和为定值的数
- 数列中和为定值的所有组合
- [算法]找数组中和为定值的数组对
- 二叉树中和为某一定值的路径
- C++求数组中和为定值的组合
- 167 Two Sum II (给定数组求相加为定值的两个数)
- 寻找二叉树中和为某一值的路径
- LeetCode 之 two Sum寻找两个相加之和为给定值的两个数
- Two sum 在数组中寻找和为指定值的两个数
- 数组中寻找和为sum的两个元素
- 8.30 PPT word excel小技巧
- zookeeper注册服务,开机自启动
- web+git
- java中流对文件的操作
- Android 7.0 bluetooth introduction
- leetcode01 Two Sum 寻找列表中和为定值的元素位置
- Apache Kafka监控之Kafka Web Console
- Python StringIO和BytesIO
- 谷歌一调皮:半个日本的网络瘫痪了
- Linq查找指定重复次数的键
- 本文从如何建立mysql索引以及介绍mysql的索引类型,再讲mysql索引的利与弊,以及建立索引时需要注意的地方 首先:先假设有一张表,表的数据有10W条数据,其中有一条数据是nickname='
- 修改限制端口访问wdcp后台
- 04.Spring Cloud学习笔记之客户端负载均衡组件Ribbon
- 递归和迭代