Two Sum

Edit

Difficulty: EASY

Categories: ๋ฐฐ์—ด/๋ฌธ์ž์—ดํ•ด์‹œ/๋งต

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


Solutions

Add Solution
JAVA 2026-09-24 17:20 Edit
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[]{map.get(complement), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
}
Notes:

[์ž๋™ ํ’€์ด ยท gpt-4.1-mini] ํ•ด์‹œ๋งต์„ ์ด์šฉํ•ด ๊ฐ ์ˆซ์ž์˜ ์ธ๋ฑ์Šค๋ฅผ ์ €์žฅํ•˜๋ฉฐ, ํ˜„์žฌ ์ˆซ์ž์™€ ๋”ํ•ด target์ด ๋˜๋Š” ์ˆซ์ž๊ฐ€ ํ•ด์‹œ๋งต์— ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค. ์žˆ์œผ๋ฉด ๋ฐ”๋กœ ์ธ๋ฑ์Šค ์Œ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ์‹œ๊ฐ„ O(n) ยท ๊ณต๊ฐ„ O(n) ์ฃผ์˜: ๊ฐ™์€ ์ˆซ์ž๋ฅผ ๋‘ ๋ฒˆ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฃผ์˜ํ•ด์•ผ ํ•˜๋ฉฐ, ์ธ๋ฑ์Šค ์ €์žฅ ์‹œ ํ˜„์žฌ ์ธ๋ฑ์Šค๋กœ ๋ฎ์–ด์“ฐ์ง€ ์•Š๋„๋ก ํ•œ๋‹ค.