https://www.acmicpc.net/problem/10816
10816번: 숫자 카드 2
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,
www.acmicpc.net
나의풀이
import java.io.*;
import java.util.*;
public class Main {
static int[] card;
public static int upperBound(int i){
int start=0;
int end=card.length;
while(start<end){
int mid=(start+end)/2;
if(card[mid]>i){
end=mid;
}else{
start=mid+1;
}
}
return start;//start가 end와 같아질 때 반복문 탈출하므로 end랑 start는 같음
}
public static int lowerBound(int i){
int start=0;
int end=card.length;
while(start<end){
int mid=(start+end)/2;
if(card[mid]>=i){
end=mid;
}else{
start=mid+1;
}
}
return start;//start가 end와 같아질 때 반복문 탈출하므로 end랑 start는 같음
}
public static void main(String args[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());//상근이가 가진 카드 개수
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());
int[] list= new int[m];
st = new StringTokenizer(br.readLine());
for(int i=0; i<m; i++){
list[i]=Integer.parseInt(st.nextToken());
}
for(int i=0; i<m; i++){
bw.write(Integer.toString(upperBound(list[i]) - lowerBound(list[i]))+" ");//중복된 수를 구하기 위해 상한, 하한 구하기
}
bw.flush();
br.close();
bw.close();
}
}
Tip.
일반적인 이진탐색과는 다르게 중복되는 값의 범위를 구해야함. upperbound lowerbound의 개념 필요
참고사이트
https://st-lab.tistory.com/267
[백준] 10816번 : 숫자 카드 2 - JAVA [자바]
https://www.acmicpc.net/problem/10816 10816번: 숫자 카드 2 첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드
st-lab.tistory.com
'코테풀이' 카테고리의 다른 글
[백준] BOJ - 2607 비슷한 단어 java 자바 (실버3) (0) | 2023.04.02 |
---|---|
[백준] BOJ - 11501 주식 java 자바 (실버2) (0) | 2023.04.02 |
[백준] BOJ - 2110 공유기 설치 자바 JAVA (골드 4) (0) | 2023.03.20 |
[백준] BOJ - 16234 인구 이동 자바 java(골드5) (0) | 2023.03.20 |
[백준] BOJ - 20437 문자열 게임 2 자바 java (골드5) (1) | 2023.03.14 |