【朱迪的LeetCode刷题笔记】1. Two Sum #Easy #C
本帖最后由 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 = , target = 9
Output:
Output: Because nums + nums == 9, we return .
Example 2:
Input: nums = , target = 6
Output:
Example 3:
Input: nums = , target = 6
Output:
Constraints:
2 <= nums.length <= 103
-109 <= nums <= 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
:type target: int
:rtype: List
"""
d = {}
for i, x in enumerate(nums):
if target - x in d:
return , i]
else:
d = i
Sol1
Python slightly better than mine
https://leetcode.com/problems/two-sum/solutions/17/here-is-a-python-solution-in-o-n-time/
class Solution(object):
def twoSum(self, nums, target):
buffer_dictionary = {}
for i in rangenums.__len()):
if nums in buffer_dictionary:
return ], 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] = i
# we insert the required number to pair with should it exist later in the list of numbers
页:
[1]