LeetCode No503.下一个更大元素 II
发布日期:2021-05-07 23:15:37 浏览次数:27 分类:原创文章

本文共 1597 字,大约阅读时间需要 5 分钟。

题目描述

在这里插入图片描述

解法一:暴力

在这里插入图片描述
时间复杂度:O(n^2),暴力竟然也能过!!

class Solution {       public int[] nextGreaterElements(int[] nums) {           //延长nums数组是原来的2倍        int[] nums1 = new int[nums.length * 2];        //复制        System.arraycopy(nums, 0, nums1, 0, nums.length);        System.arraycopy(nums, 0, nums1, nums.length, nums.length);        //暴力求解        int[] res = new int[nums.length];        for (int i = 0; i < nums.length; i++) {               int j = i + 1;            while (j < nums1.length && nums1[j] <= nums1[i]) {                   ++j;            }            if(j == nums1.length){                   //后面没有更大元素                res[i] = -1;            }else{                   res[i] = nums1[j];            }        }        return res;    }}

解法二:单调栈

在这里插入图片描述

class Solution {       public int[] nextGreaterElements(int[] nums) {           //延长nums数组是原来的2倍        int[] nums1 = new int[nums.length * 2];        //复制        System.arraycopy(nums, 0, nums1, 0, nums.length);        System.arraycopy(nums, 0, nums1, nums.length, nums.length);        int[] res = new int[nums.length];    //结果数组        Arrays.fill(res,-1);            //默认是-1        Stack<int[]> stack = new Stack<>();  //单调栈,int[0]是nums1对应的下标,int[1]是值        //单调栈        for (int i = 0; i < nums1.length; i++) {               int num = nums1[i];  //当前元素            while (!stack.isEmpty() && stack.peek()[1] < num){                   int[] pop = stack.pop();                if(pop[0] < nums.length){                       res[pop[0]] = num;                }            }            stack.push(new int[]{   i,num});        }        return res;    }}
上一篇:LeetCode No31. 下一个排列
下一篇:LeetCode No496.下一个更大元素 I

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月24日 17时05分49秒