상세 컨텐츠

본문 제목

[Leetcode] Algorithm (1)

데이터 과학

by Taeyoon.Kim.DS 2024. 4. 22. 17:08

본문

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

관련글 더보기