Java Solution – LeetCode Problem 1 Two Sum

작성자

카테고리:

← 피드로
DEV Community · V Krishnasubramaniam · 2026-06-14 개발(SW)

V Krishnasubramaniam

Problem Description:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Link to the problem

Solution:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        //map to store visited numbers along with their index
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            int requiredNum = target - nums[I];
            if(map.containsKey(requiredNum)) {
                //return the current index and the index from the map
                return new int[] {map.get(requiredNum), I};
            } else {
                map.put(nums[i], i);
            }
        }
        return null;
    }
}

Enter fullscreen mode Exit fullscreen mode

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다