从数组中寻找和的相加数
来源:互联网 发布:网络用语皮皮虾 编辑:程序博客网 时间:2024/05/19 14:19
从数组中寻找和的相加数
Two Sum
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 1
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
example 2
Given nums = [0,4,3,0], target = 0,Because nums[0] + nums[3] = 0 + 0 = 0,return [0, 3].
example 3
Given nums = [-1,-2,-3,-4,-5], target = -8,Because nums[2] + nums[4] = -3 + (-5) = -8,return [2, 4].
example 4
Given nums = [0,1,2,3,4,5,...,28888,...,65432], target = 65432,you should consider that time and space is limited.
思路
- 这个题目简单,两个for循环嵌套可以实现,但是考虑到输入数组长度大的情况下,时间复杂度太高, O(n²)
- 使用索引,遍历一次后记录nums中所有数字出现的下标,用target - nums[i]得到j,然后直接查索引中j的位置
- 索引可以用list(数组),但是nums中可能会有大数字,所需的空间太多,并且会有负数,改用dir,key为nums[i],value为i
- 同时给出简单版代码(简单版在java,C等语言在leetcode网站可以AC,但python会超时)
代码
优化版
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ idx_set = {} for i, item in enumerate(nums): idx = target - nums[i] if idx in idx_set: j = idx_set[idx] if len(j) != 0 and j[0] != i: return list([i, j[0]]) if j[0] == i and len(j) > 1: return list([i, j[1]]) else: idx_set[item] = [i]
简单版
class Solution: 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)): if nums[i] + nums[j] == target: return list([i, j])
本题以及其它leetcode题目代码github地址: github地址
阅读全文
0 0
- 从数组中寻找和的相加数
- ms 两个数组,从每个数组中取一个数相加,求最大的前k个和
- N SUM 数组中任意数相加的结果等于剩下的数相加和
- 寻找旋转数组中最小的数I和II
- 寻找数组中过半的数
- 数组中寻找重复的数
- 寻找数组中唯一的数
- 从一个含有很多不同元素的大数组中寻找10个最大的数
- 从一个数组中找出几个数,使其相加等于某个值的算法(数组元素可以重复)
- 常见面试算法题:给定数组中寻找加和为特定数的两个数
- 数组相加中第k大的数
- 从数组中找出最大的和最小的数
- 寻找数组中两个数的和为M的组合
- 从一堆(大量的)无序不重复数组成的数组中寻找一指定数出现的位置
- 在数组中寻找和为指定值的两个数
- 寻找数组中满足和为定值的两个数或所有可能组合
- 第十四题(升序数组中寻找和为特定数的两个元素)
- Two sum 在数组中寻找和为指定值的两个数
- LeetCode 56. Merge Intervals
- mac_beyond_破解
- 在myeclipse中修改工程项目的web context-root
- 精通比特币-第2章 比特币的原理
- 整理一下appintro的简单用法
- 从数组中寻找和的相加数
- 精通比特币-第3章 比特币客户端
- 野指针的定义和避免
- 精通比特币-第4章 密钥、地址、钱包
- 精通比特币-第5章 交易
- 什么是二倍图?什么是三倍图?
- 剑指Offer——在O(1)时间内删除表节点
- DAY-2
- Raspberry Pi: WiFi设置