leetcode 1. two sum
06 Oct 2017 | 알고리즘 프로그래밍문제
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
풀이코드
def two_sum(nums, target):
for idx, num in enumerate(nums):
if target - num in nums:
return idx, nums.index(target-num)
다른사람풀이
- hash table을 활용 (O(n))
def two_sum(nums,target):
dic = {}
i = 0
for num in nums:
if target - num in dic:
return dic[target-num], i
d[num] = i
i += 1