Leetcode P1 two sum @python Lang (LL)
Link: https://leetcode.com/problems/two-sum/
Content:
Method 1 - Brute Force
Algorithm:
- traverse i, first loop from 0 to len(nums-1).
- traverse j, fixed i, second loop from i+1 to len(nums).
- if nums[i] + nums[j] == target, return list
Code:
class Solution:
def twoSum(self,nums,target):
#nums = []
for i in range(len(nums) - 1):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
Time complexity:
O(n2)
Space complexity:
O(1)
Method 2 - Hash (dictionary for python)
Algorithm:
- build an empty dict keys = {}
- traverse (for loop) i
- put key-value pair into dict, keys[nums[i]] = i
- if target - nums[i] in keys, return
Code:
def twoSum(nums,target):
keys = {}
for i in range(len(nums)):
if nums[i] not in keys:
keys[nums[i]] = i
j = target - nums[i]
if j in keys:
return [keys[j], i]
Time complexity:
O(n)
Because traverse the list containing n elements only once, each look up costs only O(1).
Space complexity:
O(n)
The extra space required depends on the number of items stored in the dictionary, which stores at most n elements.