Python writes an algorithm problem every day
first day
Question: Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array and return their array subscripts.
You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice.
Source: LeetCode
Link: https://leetcode-cn.com/problems/two-sum
1. Brute force algorithm
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(0, len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return[]
2. Use dictionary to simulate hash solution
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for ind, num in enumerate(nums):
hashmap[num] = ind
# hashmap = {(2,0),(7,1),(11,2),(15,3)}
for i, num in enumerate(nums):
j = hashmap.get(target - num)
# j : 2 7 None None
if j is not None and i != j:
return [i, j]