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.
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]
runtime : 6272 ms
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for inde, num in enumerate(nums):
complement = target - num
if complement in nums[inde+1:]:
return nums.index(num), nums[inde+1:].index(complement) + (inde +1)
runtime : 1096 ms
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_map = {}
for i, num in enumerate(nums):
nums_map[num] = i
for i, num in enumerate(nums):
if target - num in nums_map and i != nums_map[target - num]:
return nums.index(num), nums_map[target - num]
runtime : 48 ms
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_map = {}
for i, num in enumerate(nums):
if target - num in nums_map:
return [nums_map[target - num], i]
nums_map[num] = i
runtime : 52 ms