中兴秋招笔试

中兴秋招笔试编程题

两个严格递增数组的逆序对

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (in.ready()) {
int res = 0;
int count = Integer.parseInt(in.readLine());
if (count == 0) {
System.out.println(res);
break;
}
String[] strings1 = in.readLine().split(" ");
int[] nums1 = new int[count * 2];
for (int i = 0; i < count; i++) {
nums1[i] = Integer.parseInt(strings1[i]);
}
String[] strings2 = in.readLine().split(" ");
for (int i = 0; i < count; i++) {
nums1[i + count] = Integer.parseInt(strings2[i]);
}
res = merge(nums1, 0, count - 1, 2 * count - 1);
System.out.println(res);

}

in.close();
}

private static int merge(int[] a, int start, int mid, int end) {
int res = 0;
int i = start, j = mid + 1;
while (i <= mid && j <= end) {
if (a[i] <= a[j])
i++;
else {
j++;
res += mid - i + 1;
}
}
return res;
}
}

等差数组

每个元素只能加1或者减1,能否组成,输出修改元素的个数,若不能,则输出-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class Main {
static int res = -1;

public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
in.readLine();
while (in.ready()) {
int count = Integer.parseInt(in.readLine());
String[] strings = in.readLine().split(" ");
if (count <= 2) {
System.out.println(0);
continue;
}
int[] nums = new int[count];
for (int i = 0; i < count; i++) {
nums[i] = Integer.parseInt(strings[i]);
}

if (nums.length < 3) {
System.out.println("0");
continue;
}
//前两个元素决定等差的差
int[] cha = {-1, 0, 1};
for (int i = 0; i < 3; i++) {
int[] B = nums.clone();
B[0] += cha[i];
for (int j = 0; j < 3; j++) {
int[] C = B.clone();
C[1] += cha[j];
dp(C, 2, Math.abs(cha[i]) + Math.abs(cha[j]));
}
}
System.out.println(res);
}
in.close();
}

//每个元素加1或减1,最少需要修改几个元素
private static void dp(int[] nums, int index, int change) {
if (index == nums.length) {
if (res == -1) {
res = change;
} else {
res = Math.min(change, res);
}
return;
}
//改变index所在的元素
int target = 2 * nums[index - 1] - nums[index - 2];
if (target == nums[index]) {
dp(nums, index + 1, change);
} else if (Math.abs(target - nums[index]) <= 1) {
nums[index] = target;
dp(nums, index + 1, change + 1);
}
}
}