728x90
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] array = new int[100];
for (int i = 0; i < array.length; i++) {
array[i] = (int)(Math.random()*30);
}
Arrays.sort(array);
while (true) {
System.out.println("찾으시는 번호를 입력해주세요.");
int target = Integer.parseInt(br.readLine());
int lowerBound = lowerBound(array,target);
System.out.println("lowerBound : "+lowerBound+" array[lowerBound] : "+array[lowerBound]);
int upperBound = upperBound(array,target);
System.out.println("upperBound : "+upperBound+" array[upperBound] : "+array[upperBound]);
System.out.println(Arrays.toString(array));
}
}
private static int lowerBound(int[] array, int target) {
int left = 0;
int right = array.length-1;
while (left <= right) {
int mid = left+(right-left)/2;
if (array[mid] < target) {
left = mid+1;
} else if (array[mid] >= target) {
right = mid-1;
}
}
return left;
}
private static int upperBound(int[] array, int target) {
int left = 0;
int right = array.length-1;
while (left <= right) {
int mid = left+(right-left)/2;
if (array[mid] <= target) {
left = mid+1;
} else if (array[mid] > target) {
right = mid-1;
}
}
return left;
}
}
728x90
반응형
'알고리즘 문제 풀이' 카테고리의 다른 글
백준 - 패션왕 신해빈(Kotlin) (0) | 2022.07.26 |
---|---|
백준 - 친구 (0) | 2022.06.15 |
나 보려고 정리한 logN 시간복잡도 (0) | 2022.01.26 |
알고리즘 기본 - 에라토스테네스의 체 (0) | 2022.01.19 |
530. Minimum Absolute Difference in BST (0) | 2021.10.18 |