您的位置:首页 > 其它

网易2017校园招聘笔试题 回文序列

2017-03-07 10:03 615 查看
如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如: 

{1, 2, 1}, {15, 78, 78, 15} , {112} 是回文序列, 

{1, 2, 2}, {15, 78, 87, 51} ,{112, 2, 11} 不是回文序列。 

现在给出一个数字序列,允许使用一种转换操作: 

选择任意两个相邻的数,然后从序列移除这两个数,并用这两个数字的和插入到这两个数之前的位置(只插入一个和)。 

现在对于所给序列要求出最少需要多少次操作可以将其变成回文序列。

输入描述: 

输入为两行,第一行为序列长度n ( 1 ≤ n ≤ 50) 

第二行为序列中的n个整数item[i] (1 ≤ iteam[i] ≤ 1000),以空格分隔。

输出描述: 

输出一个数,表示最少需要的转换次数

输入例子: 



1 1 1 3

输出例子: 

2

链接:https://www.nowcoder.com/questionTerminal/0147cbd790724bc9ae0b779aaf7c5b50

来源:牛客网

三种情况
1.首尾相等,二者删除
2.尾小,尾和倒数第二相加
3.首小,首和顺数第二相加

import java.util.Scanner;

public class Main {

public static void main(String[] arg) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
int n = scan.nextInt();
int[] arr = new int
;
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
System.out.println(solve(arr,n));
}
scan.close();
}

private static int solve(int[] arr, int n) {
int left = 0;
int right = n - 1;
int ans = 0;
while (left < right) {
if (arr[left] < arr[right]) {
arr[left + 1] += arr[left];
++left;
++ans;
}else if (arr[left] > arr[right]){
arr[right - 1] += arr[right];
--right;
++ans;
}else {
++left;
--right;
}
}
return ans;
}

}
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


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



本人以为,在这道程序中,arr[left]和arr[right]才是自变量,他们的值会影响数组的值

(Arr[left+1]或者arr[right-1]),也会影响指针的值(left、right)
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: