leetcode#1 two-sum

정은경·2022년 5월 19일
0

알고리즘

목록 보기
48/125
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        half = target // 2 
        if target % 2 == 0 and nums.count(half) >= 2:
            result = []
            for index, num in enumerate(nums):
                if num == half:
                    result.append(index)
            # print(result)
            return result
            
            
        num_index_book = {}
        
        for index, num in enumerate(nums):
            # if num >= target:
            #    continue
            num_index_book[num] = index
        
        for num in num_index_book.keys():
            num_index = num_index_book[num]
            
            left_over = target - num
            left_over_index = num_index_book.get(left_over)
            if left_over_index != None and left_over_index != num_index:
                return [num_index_book[num], num_index_book[left_over]]
profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글