[LeetCode] Two Sum

동스토리 ㅣ 2021. 8. 2. 17:19

반응형

안녕하세요.

 

LeetCode 1번 문제 Two Sum 문제풀이 하겠습니다.

 

https://leetcode.com/problems/two-sum/submissions/

 

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.

 

[TestCase]

 

[코드]

class Solution:
    def twoSum(self, nums, target):
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if target == nums[i] + nums[j]:
                    return [i,j]

[해설]

 

첫 번째 인덱스와 나머지 인덱스를 순차적으로 더해 target 값이 되면 해당 인덱스를 출력하는 방법

 

해당 방법은 Case가 적은 편에도 불구하고 Runtime이 길게 나왔다. 이는, Case가 길어질수록 Runtime이 길어진다는 의미이다.nums를 정렬하여 풀면 Runtime을 줄일 수 있을 거 같다.

 

감사합니다.

반응형

'Development > Algorithm' 카테고리의 다른 글

[LeetCode] Reverse Integer  (0) 2021.08.06
[LeetCode] Add Two Numbers  (0) 2021.08.04
[BOJ] 1012. 유기농 배추  (0) 2020.10.27
[BOJ] 11724. 연결 요소의 개수  (0) 2020.10.27
[BOJ] 10799. 쇠막대기  (0) 2020.10.27