1. Two Sum

2021. 10. 28. 18:41Leetcode

Description:

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.

 

'''
[1] brute force)

code::

for i in range(len(nums)):
    for j in range(i+1,len(nums)):
        if nums[i]+nums[j]==target:
            return [i,j]
return [-1,-1]        

-T/C: O(n^2)
-S/C: O(1)
'''

'''
[2] sorting ) 

code::
def twoSum(nums,target):
    nums.sort()         # O(logn)
    
    left,right=0,len(nums)-1
    
    while left<right:
        if nums[left]+nums[right]==target:
            return [left,right]
        elif nums[left]+nums[right]>target:
            right-=1
        else:
            left+=1
    return [-1,-1]

-T/C: O(nlogn)
-S/C: O(1)
'''

'''
[3] using hashmap)

code::
(below)

-T/C: O(n)
-S/C: O(n)
'''

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic={}
        
        for idx,num in enumerate(nums):
            if target-num in dic:
                return [dic[target-num],idx]
            else:
                dic[num]=idx
                
        return []

'Leetcode' 카테고리의 다른 글

217. Contains Duplicate  (0) 2021.10.29
222. Count Complete Tree Nodes  (0) 2021.10.28
153. Find Minimum in Rotated Sorted Array  (0) 2021.10.27
162. Find Peak Element  (0) 2021.10.27
75. Sort Colors  (0) 2021.10.27