503. Next Greater Element II - LeetCode
Description:
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.
Example 1:
Input: [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
Note: The length of given array won't exceed 10000.
Accepted
58,855
Submissions
112,982
Solution:
class Solution { public int[] nextGreaterElements(int[] nums) { boolean flag=false; int[] res = new int[nums.length]; for(int i = 0 ; i<nums.length; i++){ flag = false; for(int k = i+1; k<nums.length; k++){ if(nums[k]>nums[i]){ //System.out.println(" greater "+ nums[k]); res[i] = nums[k]; flag = true; break; } } if(!flag){ for(int m = 0; m<i; m++){ if(nums[m]>nums[i]) { //System.out.println(" greater 2 "+ nums[m] ); res[i] = nums[m]; flag = true; break; } } } if(!flag){ //System.out.println(" -1 "); res[i] = -1; } } return res; } }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
· 继承的思维:从思维模式到架构设计的深度解析
· 【保姆级教程】windows 安装 docker 全流程
· 基于Docker+DeepSeek+Dify :搭建企业级本地私有化知识库超详细教程
· 由 MCP 官方推出的 C# SDK,使 .NET 应用程序、服务和库能够快速实现与 MCP 客户端
· 电商平台中订单未支付过期如何实现自动关单?
· 上周热点回顾(3.31-4.6)