본문 바로가기
Problem Solving/LeetCode

[LeetCode] 1. Two Sum - Java

by graycode 2026. 5. 4.

 문제 링크

 

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

 

 풀이 코드

import java.util.HashMap;
import java.util.Map;

public class Solution {

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; ++i) {
            Integer v = map.get(nums[i]);
            if (map.get(nums[i]) != null) return new int[]{v, i};

            map.put(target - nums[i], i);
        }

        return null;
    }

}

댓글