[알고리즘] ep2) 사전(dictionary)
ㅇ사전(dictionary) ADT: 탐색 가능한 형태의 (key, value)쌍 항목들의 모음을 모델링주로 해시 테이블(hash table)과 이진 검색 트리(BST)로 구현하며, 이때 각 키는 유일해야 한다 -> 유일키 - 직접응용: 연
claremont.tistory.com
1. 반복문 버전: 디버깅에도 용이하고 메모리도 덜 잡아먹으므로 재귀방식보다 더 추천한다
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] arr = new int[N];
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
br.close();
}
public static int binarySearch(int[] arr, int key) {
int lowIdx = 0;
int highIdx = arr.length - 1;
while (lowIdx <= highIdx) {
int midIdx = (highIdx - lowIdx) / 2 + lowIdx;
if (arr[midIdx] < key) {
lowIdx = midIdx + 1;
} else if (arr[midIdx] > key) {
highIdx = midIdx - 1;
} else {
return midIdx;
}
}
return -1;
}
}
2. 재귀 버전: 디버깅에 용이하지 않고 메모리(스택 메모리)를 더 사용하게 되므로 추천하지는 않는다
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
br.close();
}
public static int binarySearch(int[] arr, int key, int lowIdx, int highIdx) {
if (lowIdx > highIdx) {
return -1;
}
int midIdx = (highIdx - lowIdx) / 2 + lowIdx;
if (arr[midIdx] < key) {
return binarySearch(key, midIdx + 1, highIdx);
} else if (arr[midIdx] > key) {
return binarySearch(key, lowIdx, midIdx - 1);
} else {
return midIdx;
}
}
}
(참고)
Arrays.binarySearch()는 Array 전용 이진 탐색 메서드이고
Collections.binarySearch()는 List 전용 이진 탐색 메서드이다!
'problem solving > ps java' 카테고리의 다른 글
[ps java] 피보나치 수열 알고리즘(재귀, DP) (0) | 2025.01.19 |
---|---|
[ps java] BOJ 15663 N과 M (9) 해설 (0) | 2025.01.07 |
[ps java] BOJ 15650 N과 M (2) 해설 (1) | 2025.01.06 |
[ps java] fast I/O 정확하게 알고 쓰기 (0) | 2025.01.04 |
[ps java] PriorityQueue() 사용법 (1) | 2024.10.27 |