leetcode01 Two Sum 寻找列表中和为定值的元素位置
2017-08-30 18:25
423 查看
刷刷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:
我的解法(很蠢):
解读一下别人的优质解法:
新建空字典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和当前值的位置作为结果返回。
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 solution class 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,j sol = 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_dict sol = 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和当前值的位置作为结果返回。
相关文章推荐
- 每天一道LeetCode-----寻找地增序列中第一个大于等于目标元素的位置
- leetcode之数组类之数组的旋转与分治类-----OJ 189/33/81/153/154 数组旋转 旋转数组搜索 88 有序数组合并 4 两个有序数组寻找第K个元素/中位数 35 寻找插入位置
- leetcode596:496. Next Greater Element I(寻找元素对应位置的下一个较大值)
- 小算法----寻找插入元素的位置
- Leetcode 34. 在排序数组中查找元素的第一个和最后一个位置
- 每天一道LeetCode-----摩尔投票法寻找给定数组中出现个数大于n/2或n/3的元素
- 利用折半查找,寻找元素在数组中合适恰当的位置
- leetcode 子串位置的寻找
- leetcode Majority Element 寻找出现次数最多元素
- leetcode 599. Minimum Index Sum of Two Lists 寻找index之和最小的公共元素
- leetcode 658. Find K Closest Elements 寻找绝对距离最近K个元素+ 双指针遍历
- leetcode 328 Odd Even Linked List(调整链表使得奇数位置的元素位于偶数位置元素之前)
- 【leetcode】——从两个有序数组中寻找他们并集的第k小元素
- Python实现判断并移除列表指定位置元素的方法
- leetcode 456. 132 Pattern 132模式元素寻找 + 一个很棒的利用stack的做法
- Leetcode 01 Two Sum
- [LeetCode]—Implement strStr() 寻找子串匹配第一个位置 (KMP)
- Leetcode35:Search Insert Position寻找target元素(应)插入的位置
- 在列表中选择每个元素给定位置的值,operator.itemgetter函数
- 一行代码实现对列表a中的偶数位置的元素进行加3后求和(阿里校招)