49 lines
1.3 KiB
Python

# Give a list and a number.
# Return a list of indices of two numbers
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
"""
answer = []
for i in range(len(nums)):
another = target - nums[i]
# both number in the list
if another in nums:
if nums[i] == another:
temp_list = nums.copy()
temp_list.pop(i)
if another in temp_list:
answer.append(i)
answer.append(temp_list.index(another) + 1)
return answer
if another not in temp_list:
continue
answer.append(i)
answer.append(nums.index(another))
return answer
return answer
"""
num_map = {}
for i, num in enumerate(nums):
complement = target - num
# reduce compare times
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []
test = [3, 2, 4]
TARGET_NUMBER = 6
a = Solution().twoSum(test, TARGET_NUMBER)
print(a)
test2 = [i for i in range(1, 10001)]
TARGET_NUMBER = 19999
print(test2[9998], test2[9999])
print(Solution().twoSum(test2, TARGET_NUMBER))