• [编程题] 找出前边比自己高的人的身高--字节笔试题


    找出前边比自己高的人的身高--字节笔试题

    题目描述

    存在一个多组的输入,第一行输入是有N个同学,接下来的一行分别是N个同学的身高。某同学X前的第一个比他高的同学,记录下其身高值。返回是一行每个同学对应找到的其前边的第一个比自己高的身高值。

    示例

    例如1:

    输入:

    5

    1 2 3 4 5

    输出: -1 -1 -1 -1 -1

    例如2:

    输入:

    5

    5 4 3 2 1

    输出:

    -1 5 4 3 2

    Java代码

    package ncompanydemos.p2_bytedance;
    
    import java.util.ArrayList;
    import java.util.Deque;
    import java.util.LinkedList;
    import java.util.Scanner;
    
    /**
     * @author jiyongjia
     * @create 2020/7/11 - 20:28
     * @descp:  本地idea中是ctrl+d来停止scanner的输入无法停止的问题
     */
    
    public class Exam03{
        //输入输出问题
        public static void main(String[] args){
            Scanner in = new Scanner(System.in);
    
            ArrayList<Deque<Integer>> lis = new ArrayList<>();
            while(in.hasNext()){
                int n = in.nextInt();
                int[] arr = new int[n];
                for(int i=0;i<n;i++){
                    arr[i] = in.nextInt();
                }
                //调用方法
                Deque<Integer> stack = solve(n,arr);
                lis.add(stack);
            }
    
            //遍历出结果集
            for(Deque<Integer> d : lis){
                while(!d.isEmpty()){
                    System.out.print(d.pop()+" ");
                }
                System.out.println();
            }
        }
    
        //处理算法
        public static Deque<Integer> solve(int n,int[] arr){
            Deque<Integer> stack = new LinkedList<Integer>();
            if(n==1) {
                stack.push(-1);
                return stack;
            }
    
            for(int i=arr.length-1;i>=1;i--){
                boolean flag = false;
                for(int j=i-1;j>=0;j--){
                    if(arr[j]>arr[i]){
                        stack.push(arr[j]);
                        flag = true;//代表存入了值
                        break;
                    }
                }
                //如果内层for一直没有比当前大的值,就存-1进去
                if(!flag){
                    stack.push(-1);
                }
            }
            //最外层循环是处理到i=1结束的,最前边的那个值始终放-1;
            stack.push(-1);
            return stack;
        }
    }
    

    输出

    image-20200711205247204

    在线编程时候还是没通过,只通过自测用例,估计程序时间复杂度问题吧!要么就是磨人的输入输出有问题

  • 相关阅读:
    Codeforces 845E Fire in the City 线段树
    Codeforces 542D Superhero's Job dp (看题解)
    Codeforces 797F Mice and Holes dp
    Codeforces 408D Parcels dp (看题解)
    Codeforces 464D World of Darkraft
    Codeforces 215E Periodical Numbers 容斥原理
    Codeforces 285E Positions in Permutations dp + 容斥原理
    Codeforces 875E Delivery Club dp
    Codeforces 888F Connecting Vertices 区间dp (看题解)
    Codeforces 946F Fibonacci String Subsequences dp (看题解)
  • 原文地址:https://www.cnblogs.com/jiyongjia/p/13285439.html
Copyright © 2020-2023  润新知