笔试大为4道编程题
1.给一个数组,求两个相邻数的最小值,刚开始调试只能过18%,后来发现要用long类型,送分题。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
long[] arr=new long[n];
for (int i = 0; i < n; i++) {
arr[i]=sc.nextLong();
}
long res=Math.abs(arr[1]-arr[0]);
int index=0;
for (int i = 1; i < n-1; i++) {
if (res>Math.abs(arr[i]-arr[i+1])) {
res=Math.abs(arr[i]-arr[i+1]);
index=i;
}
}
System.out.println(arr[index]+" "+arr[index+1]);
}
}
2.求一个数组中最长的子序列。以前做过原题,两种方法(二分法和dp),这道题开始用dp做的,只能过84%,后来改成二分法,ac。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
System.out.println(fun(arr));
}
private static int fun(int[] arr) {
int[] t = new int[arr.length];
int len = 0;
for (int x : arr) {
int i = 0, j = len;
while (i != j) {
int m = (i + j) / 2;
if (t[m] < x) {
i = m + 1;
} else {
j = m;
}
}
t[i] = x;
if (i == len)
++len;
}
return len;
}
}
3.举重大赛,要求小的体重是大的体重的90%以上才能参赛,问可以比多少场。
import java.util.Arrays;
import java.util.Scanner;
public class Main33 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while (sc.hasNext()) {
int m=sc.nextInt();
int[] w=new int[m];
for (int i = 0; i < w.length; i++) {
w[i]=sc.nextInt();
}
int res=0;
Arrays.sort(w);
for (int i = 0; i < w.length-1; i++) {
for (int j = i+1; j < w.length; j++) {
int min=Math.min(w[i], w[j]);
int max=Math.max(w[i],w[j]);
if (min>=max*0.9) {
res++;
}else {
break;
}
}
}
System.out.println(res);
}
}
}
4.给一个数组,改变其中元素,使其变成先递增后递减,或者递增或者递减,问最小代价。
import java.util.Scanner;
public class Main4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] num = new long[n];
for (int i = 0; i < num.length; i++) {
num[i] = sc.nextLong();
}
System.out.println(minSum(n, num));
}
public static long minSum(int n, long[] nums) {
if (n == 1)
return 0;
if (n == 2 && nums[0] == nums[1])
return 1;
if (n == 2 && nums[0] != nums[1])
return 0;
long[] temp = new long[n];
for (int i = 0; i < temp.length; i++) {
temp[i] = nums[i];
}
int i = 0;
while (i < n - 1 && nums[i] < nums[i + 1])
i++;
int j = n - 1;
while (j > 0 && nums[j] < nums[j - 1])
j--;
while (i < j) {
if (nums[i] < nums[j]) {
if (nums[i + 1] < nums[i] + 1)
nums[i + 1] = nums[i] + 1;
i++;
} else {
if (nums[j - 1] < nums[j] + 1)
nums[j - 1] = nums[j] + 1;
j--;
}
}
long res = 0;
for (int k = 0; k < n; k++) {
res = res + (nums[k] - temp[k]);
}
return res;
}
}