[Coding Test] JAVA 두 수의 합 - HashMap

LeeSeungEun·2023년 5월 17일
0

Coding Test

목록 보기
19/38

1. 문제

  • 시간복잡도 : o(n)으로 풀기

2. 코드

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

public class Main {
    public int[] Solution(int[] nums, int target) {
        HashMap<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[]{Math.min(nums[i], complement), Math.max(nums[i], complement)};
            } map.put(nums[i], i);
        }
        return new int[]{0, 0};
    }

    public static void main(String[] args) {
        Main T = new Main();
        System.out.println(Arrays.toString(T.Solution(new int[]{7, 3, 2, 13, 9, 15, 8, 11}, 12)));
        System.out.println(Arrays.toString(T.Solution(new int[]{21, 12, 30, 15, 6, 2, 9, 19, 14}, 24)));
        System.out.println(Arrays.toString(T.Solution(new int[]{12, 18, 5, 8, 21, 27, 22, 25, 16, 2}, 28)));
        System.out.println(Arrays.toString(T.Solution(new int[]{11, 17, 6, 8, 21, 9, 19, 12, 25, 16, 2}, 26)));
        System.out.println(Arrays.toString(T.Solution(new int[]{7, 5, 12, -9, -12, 22, -30, -35, -21}, -14)));
        System.out.println(Arrays.toString(T.Solution(new int[]{7, 5, 12, 20}, 15)));
        /*
        [3, 9]
        [9, 15]
        [12, 16]
        [9, 17]
        [-21, 7]
        [0, 0]
         */
    }
}

3. 풀이

0개의 댓글