马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Judie 于 2023-6-4 22:01 编辑
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]
Output: 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 <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
因为不理解returnSize是什么 这题我卡了好久qwq
Judy
Python hash table!class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i, x in enumerate(nums):
if target - x in d:
return [d[target-x], i]
else:
d[x] = i
Sol1
Python slightly better than mine
https://leetcode.com/problems/tw ... lution-in-o-n-time/class Solution(object):
def twoSum(self, nums, target):
buffer_dictionary = {}
for i in rangenums.__len()):
if nums[i] in buffer_dictionary:
return [buffer_dictionary[nums[i]], i] #if a number shows up in the dictionary already that means the
#necesarry pair has been iterated on previously
else: # else is entirely optional
buffer_dictionary[target - nums[i]] = i
# we insert the required number to pair with should it exist later in the list of numbers
|