유진정의 기록

Array_TwoSum 본문

개인공부/데이터분석&알고리즘

Array_TwoSum

알파카유진정 2024. 2. 9. 17:53

 

https://leetcode.com/problems/two-sum/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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]

 

 

 

처음 생각한 풀이, 아직 다른 자료형은 잘 못 씁니다.... 걍 리스트로 겨우 풂.

 

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        sol = []
        for i in range(len(nums)):
            target_num = target - nums[i]
            for j in range(i + 1, len(nums)):  # 현재 인덱스 이후의 요소들과만 비교
                if nums[j] == target_num:
                    return [i, j] 
        return []

 

통과는 했구여

튜플로 하면 더 빠를 것 같다네요!

enumerate 잘 안쓰는데 여기저기 자꾸 쓰라네 

담엔 써볼게ㅠ

 

from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        num_indices = {}
        for i, num in enumerate(nums):
            complement = target - num
            if complement in num_indices:
                return [num_indices[complement], i]
            num_indices[num] = i
        return []
fruits = ['apple', 'banana', 'cherry']
enumerate_fruits = enumerate(fruits)

for index, fruit in enumerate_fruits:
    print(index, fruit)
0 apple
1 banana
2 cherry

 

 

enumerate...써보려고 써봄..

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