微众银行2023.9.3 笔试编程题
题目1:切糖果
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt(); // 糖果的长度
int[] arr = new int[n]; // 糖果每一段的口味
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
// 最长长度为最后一段或者出现重复段的位置
if (i == (n - 1) || arr[i] == arr[i + 1]) {
System.out.println(i + 1);
break;
}
}
}
}
}
题目2:酷
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt(); // 橡皮泥士兵数量
int[] arr = new int[n]; // 橡皮泥士兵大小
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int num = addDiff(arr);
System.out.println(num);
}
}
// 增加差异化
private static int addDiff(int[] arr) {
int num = 0; // 需要的单位橡皮泥
boolean repeat = false; // 当前橡皮泥中是否存在重复
Arrays.sort(arr); // 排序
for (int i = 0; i < arr.length - 1; i++) {
// 如果重复则后一个大小加1
if (arr[i] == arr[i + 1]) {
repeat = true;
arr[i + 1] += 1;
num += 1;
}
}
return repeat ? num + addDiff(arr) : num;
}
}
题目三:平均值
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt(); // 数组的长度
int u = in.nextInt(); // 有理数分子
int v = in.nextInt(); // 有理数分母
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int num = 0;
double avg = (double) u / v;
for (int i = 1; i <= n; i++) { // 区间的长度
for (int j = 0; j <= n - i; j++) {
if (avg == getAvg(arr, j, j + i)) {
num++;
}
}
}
System.out.println(num);
}
}
// 求数组指定范围内的平均数(左闭右开)
private static double getAvg(int[] arr, int begin, int end) {
int sum = 0;
int len = end - begin;
for (int i = begin; i < end; i++) {
sum += arr[i];
}
return (double) sum / len;
}
}
#微众银行笔试#