zoukankan      html  css  js  c++  java
  • 网易笔试题_回文序列转换

    题目:

    如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
    {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:
    4
    1 1 1 3

    输出例子1:
    2

    java实现:

     1 package interview.test;
     2 
     3 import java.util.Scanner;
     4 
     5 /**
     6  * Created by BUAA514 on 2018-08-10.
     7  */
     8 public class NetTest1 {
     9 
    10     /*
    11     总的思路是:从数组的头尾索引分别开始计算,指导两个方向计算出的值相等即可,完了递归调用子串。
    12     计算过程中就需要对进行的“转换”进行计数操作!
    13      */
    14 
    15     public static int count = 0;
    16 
    17     public static void main(String[] args) {
    18         Scanner sc = new Scanner(System.in);
    19         int numCount = sc.nextInt();
    20         int[] inputNums = new int[numCount];
    21         for (int i=0; i<numCount; i++) {
    22             inputNums[i] = sc.nextInt();
    23         }
    24 
    25         Calculate(inputNums,0,numCount-1);
    26         System.out.println(count);
    27     }
    28 
    29     public static void Calculate(int[] arr,int startIndex,int endIndex) {
    30 
    31         int forwardValue = arr[startIndex];
    32         int backwardValue = arr[endIndex];
    33 
    34         while(forwardValue != backwardValue) {
    35             if (startIndex >= endIndex) break;
    36             // 从后往前的值大
    37             if (backwardValue > forwardValue) {
    38                 startIndex++;
    39                 forwardValue += arr[startIndex];
    40                 count++;
    41             }else {
    42                 endIndex--;
    43                 backwardValue += arr[endIndex];
    44                 count++;
    45             }
    46         }
    47         if (startIndex+1 < endIndex-1){
    48             Calculate(arr,startIndex+1,endIndex-1);
    49         }
    50     }
    51 }
    专注搬砖,擅长搬砖砸自己的脚~~~ Email: ltwbuaa@163.com
  • 相关阅读:
    UltraSoft
    UltraSoft
    UltraSoft
    UltraSoft
    UltraSoft
    2020软工提问回顾与个人总结作业
    2020软工结对项目作业-简单几何形状间交点统计
    2020软工个人博客作业-博客园班级博客分析
    2020软工个人阅读博客作业
    2020软工第一次作业-热身
  • 原文地址:https://www.cnblogs.com/TonvyLeeBlogs/p/9455912.html
Copyright © 2011-2022 走看看