LeetCode 알고리즘 : Two Sum
https://leetcode.com/problems/two-sum/
1. 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:
Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Output: [1,2]
Example 3:
Output: [0,1]```
풀이)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(len(nums)):
if i == j:
continue
if nums[i] + nums[j] == target:
num_index = [i, j]
return num_index
- 두 수를 뽑아서 두 합이
target과 같으면 된다. - 그렇기 위해서는 이중 for 문으로 리스트 안에있는 서로 다른 두 수를 순서대로 비교한 뒤 index 값을 리스트로 리턴해주면 된다.
- 이 때 서로 다른 두 수가 아닌 같은 값을 더하면 안되기 때문에 i와 j값이 같으면
continue를 통해 그 다음 for문 iter로 가게 한다.
Author And Source
이 문제에 관하여(LeetCode 알고리즘 : Two Sum), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@tk_kim/LeetCode-알고리즘-Two-Sum저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)