LeetCode 1. Two Sum - Python
Given an array of integers nums and and integer target, return the 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]
첫 번째 시도 :
class Solution:
def twoSum(self, nums, target):
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
temp = nums[i] + nums[j]
if temp == target:
return [i, j]
두 번째 시도 :
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for idx, num in enumerate(nums):
if target - num in nums:
return idx, nums.index(target-num)
세 번째 시도 :
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_map = {} #숫자라는 키가 들어가면 인덱스가 나오도록 딕셔너리를 만든다.
for i, nums in enumerate(nums):
if target - nums in nums_map: #target에서 현재 num를 뺀 것이 nums map의 key에 있으면
return[nums_map[target - nums], i] #현재의 num과 target에서 num을 뺀 배열을 return한다.
nums_map[nums] = i
참고 사이트 :
[파이썬 알고리즘 인터뷰] 7번(#1) Two Sum (www.youtube.com/watch?v=zG-ecTqsO4U)
해시테이블 : jtoday.tistory.com/73
Python enumerate 함수 : medium.com/@hckcksrl/python-enumerate-b19ad6b94c00
'Python > PS in Python' 카테고리의 다른 글
LeetCode 53. Maximum Subarray - Python (0) | 2020.09.07 |
---|---|
LeetCode 101. Symmetric Tree - Python (0) | 2020.09.04 |
LeetCode 543. Diameter of Binary Tree - Python (0) | 2020.08.25 |
LeetCode 121. Best Time to Buy and Sell Stock - Python (0) | 2020.08.24 |
LeetCode 21. Merge Two Sorted Lists - Python (0) | 2020.08.21 |
댓글