알고리즘 공부 다시 시작,,,, 가보자고
LeetCode 문제 75선 : https://www.teamblind.com/post/New-Year-Gift---Curated-List-of-Top-75-LeetCode-Questions-to-Save-Your-Time-OaM1orEU
문제
: 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.
return [i,j]
class Solution(object):
def twoSum(self, nums, target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
class Solution(object):
def twoSum(self, nums, target):
table = {num: i for i, num in enumerate(nums)}
#nums 원소들의 index로 hash table 구성
for i, num in enumerate(nums):
if ((target-num) in table) and (i != table[(target-num)]):
return [i, table[(target-num)]]
"두번째 풀이 Two-pass Hash Table은 먼저 for문으로 table이라는 해시 테이블에 nums의 인덱스와 값을 저장한 후 다시 for문을 돌려 table 내에서 원하는 complement 값을 찾는 방식이다."
class Solution(object):
def twoSum(self, nums, target):
table = {}
for i, num in enumerate(nums):
complement = target - num
if complement in table:
return [i, table[complement]]
else:
table[num] = i
"세번째 풀이 One-pass Hash Table은 두번째 풀이처럼 table이라는 해시 테이블에 nums의 인덱스와 값을 저장하지 않고, for문 한번으로 table에 값을 삽입하는 동안 현재 요소의 complement가 이미 존재하는지 확인하며, 이미 존재하는 경우 즉시 리턴을 해주는 방식이다."
<참고>