Created
July 15, 2024 21:31
-
-
Save primaryobjects/f6aa07dd9bba2470824de04c3ec56832 to your computer and use it in GitHub Desktop.
Two Sum solved in Python using brute force and hash map https://leetcode.com/problems/two-sum/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def twoSum1(self, nums: List[int], target: int) -> List[int]: | |
# O(n^2) | |
for i in range(len(nums)): | |
for j in range(i+1, len(nums)): | |
if target - nums[i] == nums[j]: | |
return [i, j] | |
return None | |
def twoSum(self, nums: List[int], target: int) -> List[int]: | |
# O(n) | |
hash = {} | |
for i in range(len(nums)): | |
current = nums[i] | |
remainder = target - current | |
if remainder in hash: | |
return [hash[remainder], i] | |
else: | |
hash[current] = i | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment