https://leetcode.com/problems/two-sum/
Two sum - The Two Sum problem is a common algorithmic challenge that can be approached in several ways depending on the desired time complexity and space complexity. Here's an overview of two primary methods to solve the Two Sum problem:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
for i in range(n - 1): # range(3) [2, 7, 11, 15] --> 2, 7, 11
for j in range(i + 1, n): # range [1, 4] --> 7, 11, 15
if nums[i] + nums[j] == target: # 9, 13, 17, 14, 18, 22, 18, 22, 26
return [i,j]
return [] # If no matching
def two_sum_hash_table(nums, target):
lookup = {}
for i, num in enumerate(nums): # key and value pair
complement = target - num
if complement in lookup:
return [lookup[complement], i]
lookup[num] = i
return []
10 Ways to use ML with GCP (0) | 2024.04.05 |
---|---|
Chi-Square - For The Perfect Understanding (0) | 2024.04.05 |
YoloV5 vs Yolov8 (0) | 2024.03.29 |
[MidJourney] A piano man (0) | 2024.03.19 |
[Terraform] State (0) | 2024.02.20 |