首页 > 试题广场 >

下一个较大元素

[编程题]下一个较大元素
  • 热度指数:6852 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个int数组A及其大小n,返回一个int数组,int数组中的元素是原数组中每个元素比他大的下一个元素,若不存在则为-1。保证数组中元素均为正整数。

测试样例:
[11,13,10,5,12,21,3],7
返回:[13,21,12,12,21,-1,-1]
推荐
思路:
从后向前维护一个递减栈。
最右边的那个值肯定没有最大值,所以肯定是-1。初始栈为-1。
从后向前计算:
(1)如果当前元素大于栈顶元素,则栈顶元素退出,如果还是大于栈顶元素,继续退出,一直遍历栈到-1或者小于栈顶元素。这个元素就是就是当前值的下一个比较大的元素。
(2)如果当前元素小于栈顶元素,栈顶元素就是当前值的下一个比较大的元素。
再简化一下代码如下
代码:
class NextElement {
public:
    vector<int> findNext(vector<int> A, int n) {
        vector<int> result;
        if(n <= 0){
            return result;
        }//if
        stack<int> stack;
        stack.push(-1);
        for(int i = n-1;i >= 0;--i){
            int top = stack.top();
            while(top != -1 && A[i] >= top){
                stack.pop();
                top = stack.top();
            }//while
            result.insert(result.begin(),top);
            stack.push(A[i]);
        }//for
        return result;
    }
};

编辑于 2015-08-16 17:03:26 回复(0)
单调栈
import java.util.*;

public class NextElement {
    public int[] findNext(int[] arr, int n) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        int[] res = new int[n];
        for(int i = 0; i < n; i++){
            if(stack.isEmpty()){
                stack.push(i);
            }else{
                if(arr[stack.peek()] > arr[i]){
                    stack.push(i);
                }else{
                    while(!stack.isEmpty() && arr[stack.peek()] < arr[i]) res[stack.pop()] = arr[i];
                    stack.push(i);
                }
            }
        }
        while(!stack.isEmpty())
            res[stack.pop()] = -1;
        return res;
    }
}

发表于 2021-11-25 22:24:43 回复(0)
import java.util.*;
/*
双重for循环
*/
public class NextElement {
    public int[] findNext(int[] A, int n) {
        // write code here
        int[] result = new int[n];
        for(int i = 0;i<n;i++){
            int temp = A[i];
            int j = i + 1;
            for(;j<n;j++){
                if(A[j] > temp){
                    result[i]=A[j];
                    break;
                }
            }
            if(j==n)
                result[i] = -1;
        }
        return result;
    }
}

发表于 2020-06-06 14:46:38 回复(0)
import java.util.*;

public class NextElement {
    public int[] findNext(int[] A, int n) {
        if(n<1)
            return null;
        int[] res=new int[n];
        for(int i=0;i<n;i++){
            res[i]=-1;
        }
        Stack<Integer> s=new Stack<Integer>();
        for(int i=0;i<n;i++){
            while(!s.isEmpty()&&A[i]>A[s.peek()])
                res[s.pop()]=A[i];
            s.push(i);
        }
        return res;
    }
}

编辑于 2017-05-04 14:14:03 回复(0)