복's

[ LeetCode - 1 ] Two Sum 본문

알고리즘/LeetCode

[ LeetCode - 1 ] Two Sum

나복이 2023. 10. 27. 20:35
728x90

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

 

Two Sum - LeetCode

Can you solve this real interview question? Two Sum - 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

leetcode.com

문제는 easy 난이도인 만큼 정말 간단한 문제이다.

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] answer = new int[2];

        for(int idx1 = 0; idx1 < nums.length -1; idx1++){
            for(int idx2 = idx1 + 1; idx2 < nums.length; idx2++){
                if(nums[idx1] + nums[idx2] == target){
                    answer[0] = idx1;
                    answer[1] = idx2;
                }
            }
        }
        return answer;
    }
}

 

아주 예전에 처음 시작할 때 Java로 풀었던게 남아있어서 봤는데 2중 loop를 사용해서 풀어서 다른 방법이 없나 solution을 참고하다가 hash를 이용한 방법이 있어서 풀어 보았다.

 

[ 📌 풀이 ]

1. target에 현재 리스트 순회중인 요소의 차를 구해서 dictionary에 있는지 확인

2 - 1. 조건 True) 현재 순회중인 요소와 ditionary의 요소의 합이 target 이기 때문에 정답으로 return 반환

2 - 2. 조건 False) 구한 차를 ditionary에 넣고 리스트 순회 재개

 

⚙︎ 정답으로 요구하는건 해당 요소의 리스트 인덱스이기 때문에 넣을 때 인덱스를 넣어줘야한다.

 

[ 📌 코드 - Python ]

class Solution(object):
    def twoSum(self, nums, target):
        hash = {}

        for idx in range(len(nums)):
            num = target - nums[idx]

            if num in hash:
                return ([hash[num], idx])
            hash[nums[idx]] = idx

 

728x90