728x90
두 수의 합
- 문제 :
https://leetcode.com/problems/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] Output: 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. 브루토 포스로 계산
def twosum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] ==target:
return [i, j]
풀이 2. in을 이용한 탐색
def twoSum(self, nums: List[int], target: int) => List[int]:
for i, n in enumerate(nums):
complement = target - n
if complement in nums[i + 1:]:
return [nums.index(n), nums[i+1:].index(complement) + (i+1)]
풀이 3. 첫 번째 수를 뺀 결과 키 조회
def twoSum(self, nums: List[int], target: int) => List[int]:
nums_map ={}
# 키와 값을 바꿔서 딕셔너리로 저장
for i, num in enumerate(nums):
nums_map[num] = i
# 타겟에서 첫 번째 수를 뺀 결과를 키로 조회
for i, num in enumerate(nums):
if target - num in nums_map and i != nums_map[target - num]:
return [i, nums_map[target - num]]
728x90
'Python > 코딩테스트' 카테고리의 다른 글
[Leetcode] 344.Reverse String (0) | 2021.06.24 |
---|---|
[Leetcode] 238. Product of Array Except Self (0) | 2021.06.23 |
[Leetcode] 125.Valid Palindrome (0) | 2021.06.22 |
[Leetcode] 121.Best tiem to Buy and Sell Stock (0) | 2021.06.21 |
[Leetcode] 42.Trappling Rainbow Water (0) | 2021.06.17 |