This is LeetCode question #1. I was wondering why LeetCode likes to use a solution class. I reformat the solution to a function without a class and call it:
def twoSum2(nums, target):
hashmap = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement in hashmap:
return [i, hashmap[complement]]
hashmap[nums[i]] = i
nums1 = [2,7,11,15]
target1 = 9
sol2 = twoSum2(nums1, target1)
print(sol2)
Output:
[1, 0]
This is LeetCode’s solution class:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for i in range(len(nums)):
complement = target - nums[i]
if complement in hashmap:
return [i, hashmap[complement]]
hashmap[nums[i]] = i
How may I call it? When I call it, my PyCharm could not even read it. It does not even understand what “List” means and I got an error. I am trying to do it but I can’t call the solution class provided by leetcode:
sol1 = Solution()
sol11 = sol1.twoSum(nums1, target1)
print(sol11)
How may I call the solution class? Would anyone write such a class in practical work? Thank you!!