Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2)
time complexity?
思路一:
要找「两数」之和,所以枚举所有「两数」的组合,从而找到对应的解
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for j in range(1, len(nums)):
for i in range(j):
if nums[i] + nums[j] == target:
return [i, j]
时间复杂度:O(n^2)
空间复杂度:O(1)
思路二:
执一搜一,将「两数」分解成:一个已知和一个未知。从而转化成:在一个「无序」数组中搜索一个给定数字。只搜一次的话简单遍历即可,此时我们只使用O(1)的辅助空间,而现在的问题是「在一个不断插入新数字的<序列>中,如何快速查找到某一个数字?」这里的<序列>也可以叫做<容器>,即使用辅助存储空间的情况。为了追求速度,我们选择hash表作为辅助存储结构。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
index = {}
for i, x in enumerate(nums):
if target - x in index:
return [index[target - x], i]
else:
index[x] = i
时间复杂度:O(n)
空间复杂度:O(n)
标签:index,return,target,nums,int,Sum,Two,复杂度,LeetCode From: https://www.cnblogs.com/battle-angel-tears/p/18077090