티스토리 뷰

PYTHON

[LeetCode/PYTHON] Two Sum

U_pic 2022. 1. 17. 23:43

● 문제 링크

 

Two Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


● 문제 설명

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.

● 문제 해결 방향

알고리즘 자체가 복잡하지 않아 보여서 시간을 단축시키는 것에 집중을 해봤습니다.

먼저 접근한 방식으로는 반복문을 많이 사용해야하는 단점이 있어서

최대한 반복문 최대한 적게 사용하는 방식을 생각해 보았습니다.


● 문제 해결 코드

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        
        for i in range(len(nums)):
            x = target - nums[i]
            if x in nums[i+1:]:
                return [i, nums[i+1:].index(x) + i + 1]

 

반복문을 돌리면서

target에 현재 순서의 숫자를 빼주고

그 숫자가 현재 순서 이후에 존재하는 숫자 배열에 포함되어있는 지를 확인하고

있다면 그 결과값을 return 해주었습니다.


● 알게 된 것 / 아쉬운 점

 

.index() 사용이 찝찝해서 zip()를 통해 인덱스를 우선 할당해주고 비슷하게 연산해보았지만

부분 배열을 구하는 부분에서 zip을 사용할 수 없었다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함