Two Sum - LeetCode

김견지·2025년 3월 11일
0

LeetCode

목록 보기
1/13
post-thumbnail

Submission Link

Question

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.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: 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]

Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

My Solutioin

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i, num in enumerate(nums):
            if target - num in nums:
                j = nums.index(target - num)
                if i != j:
                    break
        return [i, j]

First I thougt of Exhaustive Search (Brute Force Alg.) using Combination.
But since it must be latest solution, I tried to think of another solution and use python library.

Feedback

Python Grammar

index()

a = [1, 2, 3]
a.index(1)  # return 0. index of element
a.index(4)  # ValueError if 4 is not in a

a = [2, 2, 3, 5]
a.index(2)  # return 0. minimum index

a = [5, 3, 4, 5, 5, 6, 7]
# find index of 5 in between index 2 ~ index 5
a.index(5, 2, 5). # return 3.

find()

is for String. not for List

p.s.

Try - Except was slower than in

Better Solution?

Fastest Sol.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        pair={}
        for i,num in enumerate(nums):
	        # paring 0 ~ i-1 th and i th value
            if target-num in pair:
                return [i,pair[target-num]]
            # don't need to add O(N) to make hash map. cool!
            pair[num]=i

Comment

No one is using python lib.. Is it because of efficiency? or is it not allowed? : /

profile
ML Engineer / Autonomous driving

0개의 댓글