【写在前面:还在上学,七月入职,实在太闲,小记一下,菜猫一只,欢迎交流。】
今天第一天,从第一题刷起,大名鼎鼎的two sum,在这里总结一下所有变形题。
【1. two sum】
解法:
1. brute force: loop through each element x by using two for loop.
- time complexity: O(n^2), n is the length of the array
- space complexity: O(1)
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]
2. Hash table
- time complexity: O(n), n is the length of the array
- space complexity: O(n), for the hash table, n is the length of the array
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
m &