• 求每日大于此日温度需要的天数


    1,常规的想法是用两个指针,1个指向要判断的元素,另一个找到大于此元素的元素下标

    2,但这个算法的时间复制度是O(n^2)

    3,我们可以使用栈来解决此类问题

    4,便利元素,当元素小于栈顶元素时,元素进栈;

    5,当元素大于栈顶元素时,则计算栈顶元素与当前元素的距离

    6,如此时间复制度为O(n)

    import java.util.*;
    
    public class Client {
        public static void main(String[] args) {
                           //  0   1 2  3  4  5  6  7
            int[] templates = {23,24,25,21,19,22,26,23};
            int[] wendu = wendu(templates);
            System.out.println(Arrays.toString(wendu));
        }
    
        static int[] wendu(int[] templates ) {
            int[] result = new int[templates.length];
            Stack<Integer> stack = new Stack<>();// 保存的是数组的下标
            for (int i = 0; i < templates.length; i++) {
                if(stack.isEmpty() ){
                    stack.push(i);
                }else {
                    Integer peek = stack.peek();
                    if(templates[i] <= templates[peek]){
                        stack.push(i);
                    }else {// 比栈顶元素大
                        while (!stack.isEmpty()){
                            Integer index = stack.pop();
                            if(templates[i] > templates[index]){
                                result[index] = i - index;
                            }else {
                                stack.push(index);
                                break;
                            }
                        }
                        stack.push(i);
                    }
                }
    
            }
    
            return result;
        }
    
    }
  • 相关阅读:
    C++ std::stack 基本用法
    linux6 安装 ntopng
    linux 6安装 redis2.6
    Linux6搭建Tomcat服务器
    EXSI6.5忘记root密码
    python3笔记--数字
    python3笔记--运算符
    python3基本数据类型
    python3笔记
    centos6.X升级python3.X方法
  • 原文地址:https://www.cnblogs.com/dongma/p/12734898.html
Copyright © 2020-2023  润新知