Two Sum and the use of Dictionary (Easy) | LeetCode Practice #1

작성자

카테고리:

← 피드로
DEV Community · 睡觉 · 2026-07-10 개발(SW)

睡觉

睡觉

Posted on Jul 10 • Edited on Jul 14

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.

Python

####Double Loops (Runtime: 2441ms, Memory: 13.4MB)
    #DECLARE nums: ARRAY of INTEGER
    #DECLARE target: INTEGER
class Solution:
    def twoSum(self, nums, target):
        length = len(nums)
        for i in range(length-1):
            for j in range((i+1), length):
                if nums[i] + nums[j] == target:
                    return i, j
        return None



####Hashing Algorithm (Runtime: 0ms, Memory: 12.8MB)
    #DECLARE nums: ARRAY of INTEGER
    #DECLARE target: INTEGER
class Solution:
    def twoSum(self, nums, target):
        seen_map = {}
        for i, value in enumerate(nums):
            if (target-value) in seen_map:
                return seen_map[target-value], i
            seen_map[value] = i
        return None

Enter fullscreen mode Exit fullscreen mode

Thoughts

I think the most important thing that the Two Sum question teaches is how to use Dictionaries effectively. It helps you understand that using Direct Access is much faster than looping through all the elements. Personally, it made me step back and think more about improving performance rather than simply solving the problem.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다