Created
February 21, 2020 04:56
-
-
Save conquerex/158c03a9e6ed1059aab1a6680a940cd5 to your computer and use it in GitHub Desktop.
두 개의 수들의 인덱스들을 반환하는 함수를 작성하라.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 두 개의 수들의 인덱스들을 반환하는 함수를 작성하라. | |
// 반환되는 두 개의 수의 합은 주어진 목표 정수 값과 동일해야 한다. 단, 복잡도는 O(n)이어야 한다. (가능한 주어진 입력 배열을 한번만 읽는다.) | |
// input : [2, 5, 7, 11, 15, 4], 9 | |
// output : [0, 2] | |
import java.util.HashMap; | |
class Solution { | |
public int[] solution(int[] arrayParam, int targetParam) { | |
// e.g. arrayParam = [2, 5, 7, 11, 15, 4] | |
// e.g. targetParam = 9 | |
HashMap map = new HashMap(); // 복잡도 : O(1) | |
int[] answer = new int[2]; // 쌍의 인덱스가 필요하므로 크기는 2 | |
for (int i = 0; i < arrayParam.length; i++) { | |
// e.g. (3번째) 2 = 9 - 7 | |
int value = targetParam - arrayParam[i]; | |
if (map.containsKey(value)) { | |
answer[0] = (int) map.get(value); | |
answer[1] = i; | |
return answer; | |
} | |
// 기존맵에 value값이 없으면 array에 있는 값을 맵에 추가 | |
map.put(arrayParam[i], i); | |
} | |
return null; // 해당없음 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment