[leet_code] Two Sum

오현우·2022년 3월 28일
0

알고리즘

목록 보기
2/25
post-thumbnail

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.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

체크해야할 점

  1. nums 리스트를 정렬해서는 안된다.
  2. nums들은 음수도 포함된다.
  3. 단순히 brute force로 풀 수 있지만, 더 나은 방법이 있는지 체크해야 한다.

해결방법

  1. brute force 방법으로 해결하기
  2. memoizaition 방법

Burte Force

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i, number in enumerate(nums):
            for j in range(i+1, len(nums)):
                temp = number + nums[j]
                if temp == target:
                    return [i, j]
                

Memoziation

class Solution:
   def twoSum(self, nums: List[int], target: int) -> List[int]:
       seen = {}
       for i, number in enumerate(nums):
           remaining = target - nums[i]
           
           if remaining in seen:
               return [i, seen[remaining]]
            
           seen[number] = i 
profile
핵심은 같게, 생각은 다르게

0개의 댓글