您的位置:首页 > 其它

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

2016-10-08 23:01 459 查看
如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
{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),以空格分隔。



输出描述:

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



输入例子:

4
1 1 1 3



输出例子:

2


[html] view
plain copy

package com.wangyi.xiaozhao;  

  

import java.util.Scanner;  

  

public class AnHeiZiFuChuan {  

  

    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;  

    }  

  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: