关于LeetCode的股票跨度问题是否有更好的解决方案?

问题描述 投票:0回答:1

我在2020年5月19日进行了Leetcode挑战,这是在线股票跨度。其描述如下:

“编写一个StockSpanner类,该类收集某些股票的每日价格报价,并返回该股票当天的价格跨度。股票价格今天的跨度被定义为股票价格小于或等于今天价格的连续的最大天数(从今天开始并向后倒退)。“

我使用一种使用堆栈的方法,该堆栈保存大小为2的int数组,其中索引0存储价格,索引1存储该价格的跨度。我提交并通过了,但仅超过Java提交的30%。但是,在YouTube上找到的解决方案使用了与我相同的方法,只是使用了几种不同的语言,包括Java和Python。

链接到YouTube解决方案:https://www.youtube.com/watch?v=lGWLBgwd-cw&t=64s

链接到LeetCode:https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/536/week-3-may-15th-may-21st/3334/

有人可以更好地解决这个问题吗?

下面是我的代码:

public class StockSpanner1 {
    Stack<int[]> prices;

    public StockSpanner1() {
        prices = new Stack<>();
    }

    public int next(int price) {
        int span = 1; // All inputs will start with span of 1

        // While the top price is less than the new price, sum the spans
        while (!prices.isEmpty() && prices.peek()[0] <= price) {
            span += prices.pop()[1]; // Sum the spans and pop the top
        }

        prices.push(new int[]{price, span}); // Add the new price with its span

        return span; // Return the span
    }
}
java algorithm
1个回答
0
投票

`

public class StockSpanner {
    Stack<Node> stack;
    int index;

    public StockSpanner()    //default constructor
    {
       this.stack=new Stack<>();
       this.index=0;
    }

    public int next(int price) {
        while(!stack.isEmpty() && stack.peek().val<=price){
            stack.pop();
        }
        int span=0;
        if(stack.isEmpty())  
            span = index+1;
        else 
            span = index-stack.peek().index+1;
        stack.push(new Node(price,++index));
        return span;
    }
}

class Node {
    int val;
    int index;

    public Node(int val,int index){
        this.val=val;
        this.index=index;
    }
}

`

这是我的解决方案,希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.