Published:
Updated:


Solution

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

public class TwoSum {
    // Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
    // O(n)
    public static int[] twoSum(int[] nums, int target) {
        int[] answer = new int[]{};
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            // nums[n] + nums[m] = target
            // nums[m] = target - nums[n]
            // key ๊ฐ’์ด target - nums[i]์— ํ•ด๋‹น๋˜๋Š” index ์ €์žฅ ํ›„ break
            if (map.containsKey(target - nums[i])) {
                answer = new int[]{map.get(target - nums[i]), i};
                break;
            }

            map.put(nums[i], i); // if ์กฐ๊ฑด์— ๋งž์ง€ ์•Š๋‹ค๋ฉด key์— index ์ €์žฅ
        }
        return answer;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[]{2, 7, 11, 15}, 9)));
        System.out.println(Arrays.toString(twoSum(new int[]{3, 2, 4}, 6)));
        System.out.println(Arrays.toString(twoSum(new int[]{3, 3}, 6)));
    }
}

Leave a comment