zoukankan      html  css  js  c++  java
  • 找出数组中右边比我小的元素

    【题目】一个整数数组A,找到每个元素:右边第一个比我小的下标位置,没有则用-1表示

    输入:[5,2]

    输出:[1,-1]

    解释:因为元素5的右边离我最近且比我小的位置应该A[1],最后一个元素2右边没有比2小的元素,所以应该输出-1

    package leetcode;
    
    import java.util.HashMap;
    import java.util.Stack;
    
    public class FindRSmallSolution {
        int[] findRightSmall(int[] A){
            //结果数组
            int[] ans = new int[A.length];
    
            //注意,栈中元素记录的是下标
            Stack<Integer> t = new Stack();
            for(int i = 0 ; i< A.length ;i++){
                final int x = A[i];
                //每个元素都向左遍历栈中的元素完成消除动作
                while(!t.empty() && A[t.peek()] > x){
                    //x消除的时候,记录一下被谁消除了
                    ans[t.peek()] =i ;
                    //消除的时候,值更大的需要从栈中消失
                    t.pop();
                }
                //剩下的入栈
                t.push(i);
            }
            //栈中剩下的元素,由于没有人能消除他们,因此,只能将结果数组为-1
            while(!t.empty()){
                ans[t.peek() ]= -1;
                t.pop();
            }
            return ans;
        }
        int[] findRightSmall2(int[] arr){
            int[] res = new int[arr.length];
            if(arr.length == 1){
                res[arr.length-1] = -1;
                return  res;
            }
            for(int i= 0 ;i <arr.length ;i++){
                int flag =-1;
                for(int j=i+1 ;j < arr.length; j++){
                    if(arr[i] > arr[j]){
                        flag= 1;
                        res[i]=j;
                        break;
                    }
                }
                if(flag !=1){
                    res[i] =-1;
                }
            }
            return res;
        }
        public static void main(String[] args){
            FindRSmallSolution fs = new FindRSmallSolution();
            int[] arr= {1,2,4,9,4,0,5};
             int[] f =fs.findRightSmall2(arr);
             int[] e = fs.findRightSmall(arr);
            for(int h=0; h< f.length;h++){
                System.out.println(f[h]);
            }
            System.out.println("===========================");
            for(int n=0; n< f.length;n++){
                System.out.println(e[n]);
            }
        }
    }
  • 相关阅读:
    面向对象的继承关系体现在数据结构上时,如何表示
    codeforces 584C Marina and Vasya
    codeforces 602A Two Bases
    LA 4329 PingPong
    codeforces 584B Kolya and Tanya
    codeforces 584A Olesya and Rodion
    codeforces 583B Robot's Task
    codeforces 583A Asphalting Roads
    codeforces 581C Developing Skills
    codeforces 581A Vasya the Hipster
  • 原文地址:https://www.cnblogs.com/goodtest2018/p/14855853.html
Copyright © 2011-2022 走看看