Problem Description
Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value target in the array, and return their array subscripts.
You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.
You can return answers in any order.
test case
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, 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]
hint:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
There will only be one valid answer
Solution 1: (violent enumeration)
Time complexity: O(n²) Space complexity: O(1)
The code is as follows (example):
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return i,j
Solution two
Idea: judge whether num2 = target - num1 is also in nums. If you find its index directly with nums.index
Time complexity: O(n) Space complexity: O(n)
The code is as follows (example):
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
l=len(nums)
for i in range(l-1):
num1=nums[i+1:l]
if (target-nums[i]) in num1:
j=nums.index(target-nums[i],i+1)
return [i,j]
Solution three (excellent)
Idea: Create a hash table. For each x, we first query whether target - x exists in the hash table. If not, insert x into the hash table. Time complexity: O(n) Space complexity
: The O(n)
code is as follows (example):
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash=dict()
for index,value in enumerate(nums):
if target-nums[index] in hash:
return [index,hash[target-nums[index]]]
else:
hash[value]=index
return []
Summarize
I haven't looked at the code for a long time, and I forgot something. . .