zoukankan      html  css  js  c++  java
  • 网易真题之回文序列

    题目描述:

    如果一个数字序列逆置之后跟原序列是一样的就称这样的数字序列为回文序列。例如:
    {1, 2, 1}, {15, 78, 78, 15} , {112} 是回文序列,
    {1, 2, 2}, {15, 78, 87, 51} ,{112, 2, 11} 不是回文序列。
    现在给出一个数字序列,允许使用一种转换操作:
    选择任意两个相邻的数,然后从序列移除这两个数,并用这两个数字的和插入到这两个数之前的位置(只插入一个和)。
    现在对于所给序列要求出最少需要多少次操作可以将其变成回文序列。

    分析:

    比较第一个和最后一个,如果第一个大,则最后两个相加替换原来位置。如果首尾元素相等,则删除首尾元素。

    package project001;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class Main07 {
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int nums = in.nextInt();
            List<Integer> list = new ArrayList<Integer>();
            
            for(int i=0;i<nums;i++){
                list.add(in.nextInt());
            }
            System.out.println(getSum(list));
    
    
        }
        public static int getSum(List<Integer> list){
            if(list.size()<=1) return 0;
            int operation = 0;
            while(list.size()>1){
                if(list.get(0)>list.get(list.size()-1)){
                    int a = list.get(list.size()-2);
                    int b = list.get(list.size()-1);
                    list.set(list.size()-2, a+b);
                    list.remove(list.size()-1);
                    operation++;
                }else if(list.get(0)<list.get(list.size()-1)){
                    int a = list.get(0);
                    int b = list.get(1);
                    list.set(0, a+b);
                    list.remove(1);
                    operation++;
                }else{
                    list.remove(0);
                    list.remove(list.size()-1);
                }
            }
            return operation;
        }
    }
  • 相关阅读:
    json数组解析
    sparkschedule任务类
    elasticsearch的操作类
    删除hbase的region步骤和代码
    zookeeper持有者类
    zookeeper主节点竞争类
    剑指offer(61-66)编程题
    Codeforces Round #190 (Div. 2) B. Ciel and Flowers
    一些傍晚的感想
    Codeforces Round #307 (Div. 2) D. GukiZ and Binary Operations
  • 原文地址:https://www.cnblogs.com/wuchaodzxx/p/5868315.html
Copyright © 2011-2022 走看看