Silver Library (Archived)
Two Sum - Note 본문
First attempt:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
array = {}
for i, n in enumerate(nums):
mediator = target - n
if mediator in array:
return [array[mediator], i]
else:
return False
return
- used blank array to use dictionary, mapping. (to not change its default array)
- used enumerate to mark both as differently.
- array dynamically refer to mediator, so it works with/under array's will.
- as hashmap, input key value. i represents each new number from its integer nums. (brute force)
- to state 'otherwise, do not', I return False. Looks like this is the error.
(the purpose was to let program compile as intended. -
in this case: I want to let it roll and scan each value from nums first, then target should substract each value from the beginning until it detects the target value = that match to the sum of its given integer value, nums.)
Once I explain this by myself, I realised one thing.
If that so...
Second attempt:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
array = {}
for i, n in enumerate(nums):
diff = target - n
if diff in array:
return [array[diff], i]
"""
in the array, there is nums,
and there is new value to take brute force attack
for each value to compare and detect the target value.
array OK
n with array OK
new value for i OK
# the goal :
both target value = the value in array of its integer (each value, brute force)
array[diff] = i ?
Miss! that process was compilled already above.
array[nums] = i ?
"""
array[n] = i
return
Time spending : 53 mins.
Tip: write down my understanding somewhere in a plain English, then try code it based on its info.
referred:
https://www.geeksforgeeks.org/hash-map-in-python/
'F2. Problem & Solving > Solving' 카테고리의 다른 글
To lower case - python (0) | 2022.04.07 |
---|---|
Finally... (0) | 2022.03.17 |
오랜만의 공개글. (0) | 2022.03.12 |
Types of algorithm (0) | 2022.02.14 |
10869, 2588 사칙연산 - Python [특이사항] (0) | 2021.12.26 |