본문 바로가기

컴퓨터/LeetCode

LeetCode 1 Two Sum Easy [Java]

문제: 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

1. 코드

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] answer = new int[2];
        int diff;
        for(int i = 0; i < nums.length; i++) {
            diff = target - nums[i];
            if(map.containsKey(diff)) {
                answer[0] = map.get(diff);
                answer[1] = i;
                break;
            }
            map.put(nums[i], i);
        }
        return answer;
    }
}

2. 설명

HashMap을 이용하여 target - nums[i] 값이 있다면 해당 값의 인덱스와 i의 값을 answer에 저장하고 answer 반환 후 종료합니다. 만약 존재하지 않으면 map에 해당 값을 저장하고 계속해서 진행합니다.