
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; }}
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月24日 17时05分49秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
windows消息机制(转)
2021-05-09
STL笔试面试题总结(干货)(转)
2021-05-09
XML 和 HTML 之间的差异
2021-05-09
阿里钉钉面试题
2021-05-09
华为社招笔试
2021-05-09
C++中找资源或者函数的方法
2021-05-09
一些留给自己的思考题(只求回过头来能够有所获)
2021-05-09
SQL函数返回表的写法
2021-05-09
delete对象时会自动调用类的析构函数
2021-05-09
C++ 子类对象直接赋值给父类对象可行,反过来不行
2021-05-09
linux下同一个动态库名为何辣么多的.so文件
2021-05-09
SQL联表的方式(逗号, Left Join, Right Join)
2021-05-09
牛客网输入输出举例
2021-05-09
字符串初始化时的注意点
2021-05-09
软考相关试题
2021-05-09
顺序表的操作
2021-05-09
常量表达式
2021-05-09
POD类型
2021-05-09
const与常量,傻傻分不清楚~
2021-05-09
Head First设计模式——迭代器模式
2021-05-09