[leetcode] 1. Two Sum

Joy·2022년 10월 12일
0

Coding Test

목록 보기
45/48

Q

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.

A

 def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # sortnums = sorted(nums)
        n = 0
        while n < len(nums):
            for i in range(n+1,len(nums)):
                if nums[n]+nums[i] == target:
                    return sorted([n,i])
            n = n+1

solution

  • used enumerate(list) function to get index and element at the same time.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        prevMap = {}  # val -> index

        for i, n in enumerate(nums):
            diff = target - n
            if diff in prevMap:
                return [prevMap[diff], i]
            prevMap[n] = i
profile
roundy

0개의 댓글