반응형
📖 문제
📃 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(br.readLine());
int[] card = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < N; i++) {
card[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(card);
int M = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < M; i++) {
int key = Integer.parseInt(st.nextToken());
sb.append(upperBound(card, key) - lowerBound(card, key)).append(' ');
}
System.out.println(sb);
}
private static int lowerBound(int[] card, int key) {
int lo = 0;
int hi = card.length;
// loop when lo = hi
while (lo < hi) {
int mid = (lo + hi) / 2;
// if key(second input number) is repetition or lower
// -> search lower index for length of repitition
if (key <= card[mid]) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
private static int upperBound(int[] card, int key) {
int lo = 0;
int hi = card.length;
// loop when lo = hi
while (lo < hi) {
int mid = (lo + hi) / 2;
// if key(second input number) is lower than mid
// -> search lower index for upperBound
if(key < card[mid]){
hi = mid;
}else{
// repitition number is +1 index for search upperBound
lo = mid + 1;
}
}
return lo;
}
}
🔗 링크
https://www.acmicpc.net/problem/10816
'Study & Project ✏️ > 알고리즘 📋' 카테고리의 다른 글
백준[JAVA] 1259.팰린드롬수 - 자바 (0) | 2022.10.30 |
---|---|
백준[JAVA] 11866.요세푸스 문제 0 - 자바 (0) | 2022.10.30 |
백준[JAVA] 11050.이항 계수 1 - 자바 (0) | 2022.10.23 |
백준[JAVA] 10866.덱 - 자바 (2) | 2022.10.23 |
백준[JAVA] 2164.카드2 - 자바 (0) | 2022.10.20 |