1.统计每个分数出现的次数**: 创建一个长度为 101 的数组 count,用于统计每个分数出现的次数。
计算前缀和: 创建一个长度为 101 的数组 prefixSum,用于存储小于等于某个分数的学生数量。
import java.util.Arrays;
public class Main {
public static int solution(int[] arr) {
Arrays.sort(arr);
int[] cnt = new int[101];
for(int score : arr){
cnt[score]++;
}
int[] prefixSum = new int[101];
for(int i = 1; i < 101; i++){
prefixSum[i] = prefixSum[i - 1] + cnt[i];
}
int ans = 0;
int n = arr.length;
for(int score : arr){
int left = prefixSum[score];
int right = n - left;
if(left > right){
ans++;
}
}
return ans;
}
public static void main(String[] args) {
// Test cases
System.out.println(solution(new int[]{100, 100, 100}) == 3); // Output: true
System.out.println(solution(new int[]{2, 1, 3}) == 2); // Output: true
System.out.println(solution(new int[]{30, 1, 30, 30}) == 3); // Output: true
System.out.println(solution(new int[]{19, 27, 73, 55, 88}) == 3); // Output: true
System.out.println(solution(new int[]{19, 27, 73, 55, 88, 88, 2, 17, 22}) == 5); // Output: true
}
}
2.二分:查找找到第一个大于 score 的位置 idx。
import java.util.Arrays;
public class Main {
public static int solution(int[] arr) {
Arrays.sort(arr);
int n = arr.length;
int ans = 0;
for(int score : arr){
int index = binarySearch(arr, score);
int leftNum = index;
int rigthNum = n - leftNum;
if(leftNum > rigthNum){
ans++;
}
}
return ans;
}
public static int binarySearch(int[] arr, int target) {
int left = 0;
int rigth = arr.length - 1;
while(left < rigth){
int mid = left + (rigth - left) / 2;
if(arr[mid] > target){
rigth = mid - 1;
}else{
left = mid + 1;
}
}
return left;
}
public static void main(String[] args) {
// Test cases
System.out.println(solution(new int[]{100, 100, 100}) == 3); // Output: true
System.out.println(solution(new int[]{2, 1, 3}) == 2); // Output: true
System.out.println(solution(new int[]{30, 1, 30, 30}) == 3); // Output: true
System.out.println(solution(new int[]{19, 27, 73, 55, 88}) == 3); // Output: true
System.out.println(solution(new int[]{19, 27, 73, 55, 88, 88, 2, 17, 22}) == 5);
}
}