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.

 

 

풀이

 

 

리스트 안의 원소중 2개의 원소가 합쳐져서 target의 값이 되는 인덱스를 나타내면 되는 문제이다.

 

문제를 보고 그냥 투포인터로 하면 완전탐색 하면되는거 아닌가? 라고 생각했었다, 하지만 출제 주제는 해시테이블 관련 문제라고 되어있었기에,  생각을 해봤다,  단순하게 해시테이블에 각각의 값을 키로, 인덱스를 값으로 넣는다, 

 

 

class Solution(object):
    def twoSum(self, nums, target):
        dict = {}
        result = []
        for i in range(len(nums)):
            check_num = target - nums[i]
            if check_num in dict:
                result = [dict[check_num],i]
                break
            dict[nums[i]]= i

        return result
        
        
        
  #sudo
  
  def twoSum(self, nums, target):
    dict = 빈 해시테이블
    result = 리턴 할 값 []
    for i in range(찾아야할 배열): 
         해쉬테이블 키 = 찾아야 할 값 - 현재 값  
        if 해시테이블 키 in 해시테이블: 해시테이블 안에 동일한 키가 존재한다면 
            result = [현재 해쉬테이블 키, 현재 인덱스]
            break 반복문 종료 
     	 dict[현재 인덱스의 값]=현재인덱스 만일 존재하지 않는다면 해시테이블에 인자 추가

    return result

 

다른사람의 코드

 

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict={}
        for i,n in enumerate(nums):
            if n in dict:
                return dict[n],i
            else:
                dict[target-n]=i
    #please upvote me it would encourage me alot

eumerate함수를 사용해서 인덱스와 값을 뽑아서 넣어준다, 다음에는 emurate도 사용해봐야겠다.

 

'알고리즘 > LeetCode' 카테고리의 다른 글

219. Contains Duplicate II  (0) 2023.08.31
150. Evaluate Reverse Polish Notation  (0) 2023.08.31
LeetCode 155. Min Stack  (0) 2023.08.31
LeetCode 35. Search Insert Position  (0) 2023.08.29
LeetCode 141. Linked List Cycle  (0) 2023.08.29

+ Recent posts