Notice
Recent Posts
Recent Comments
Link
오늘도 개발
26. Two Sum II - Input array is sorted 본문
문제
인수로 들어오는 numbers 리스트는 오름차순으로 정렬되어 있다.
여기서 더하면 target 숫자가 되는 두 요소의 인덱스를 리스트로 반환하시오.
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
내가 해결한 방식
ref 딕셔너리에 target - 현재값으로 된 키가 존재하는지 확인.
존재하면 반환, 존재하지 않으면 현재값:i를 딕셔너리에 추가.
def twoSum(nums, target):
ref = {}
for i in range(len(nums)):
if ref.get(target - nums[i]) != None:
return [ref[target - nums[i]], i]
ref[nums[i]] = i
return []'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글
| 28. Rotate Array (0) | 2022.10.17 |
|---|---|
| 27. Minimum Size Subarray Sum (0) | 2022.10.15 |
| 25. Array Partition I (1) | 2022.10.14 |
| 24. Reverse String (1) | 2022.10.14 |
| 23. Longest Common Prefix (0) | 2022.10.14 |