博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
503. Next Greater Element II
阅读量:2350 次
发布时间:2019-05-10

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

题目

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.

我的想法

正向走一遍,再反向走一遍把第一遍没找到的与前面比较

我觉得这道题的test cases真的傻逼透了。找不到返回-1,为什么要有[1,8,-1,-100,-1,222,1111111,-111111]这样的test case???????真的写的火大

class Solution {
public int[] nextGreaterElements(int[] nums) {
if(nums == null || nums.length <= 0) {
return new int[0]; } if(nums.length == 1) {
int[] res = {
-1}; return res; } int[] res = new int[nums.length]; Arrays.fill(res, -1); int idxRes = 0; while(idxRes < nums.length - 1) {
int idxNums = idxRes + 1; while(idxNums < nums.length) {
if(nums[idxNums] > nums[idxRes]) {
res[idxRes] = nums[idxNums]; break; } idxNums++; } idxRes++; } idxRes = 1; while(idxRes < nums.length) {
int idxNums = 0; while(res[idxRes] != -1) {
idxRes++; if(idxRes >= nums.length) {
break; } } while(idxNums <= idxRes) {
if(nums[idxNums] > nums[idxRes]) {
res[idxRes] = nums[idxNums]; break; } else {
idxNums++; } } idxRes++; } return res; }}

解答

Leetcode solution: Stack

很聪明的方法,用一个stack来模拟循环的过程。感觉循环类的题都可以用stack来模拟

class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack
stack = new Stack<>(); int[] res = new int[nums.length]; for(int i = nums.length - 1; i >= 0; i--) {
stack.push(nums[i]); } for(int i = nums.length - 1; i >= 0; i--) {
while(!stack.isEmpty() && stack.peek() <= nums[i]) {
stack.pop(); } if(stack.isEmpty()) {
res[i] = -1; } else {
res[i] = stack.peek(); } //把自己push进去,便于前一个元素比较 stack.push(nums[i]); } return res; }}

转载地址:http://pyqvb.baihongyu.com/

你可能感兴趣的文章
关于C++中野指针的说明
查看>>
DirectShow中常见的RGB/YUV格式
查看>>
DirectShow系列讲座之一——DirectShow系统概述
查看>>
DirectShow系列讲座之二——Filter原理
查看>>
DirectShow系列讲座之三——开发自己的Filter
查看>>
DirectShow应用——支持Windows Media格式
查看>>
WDM 视频捕获介绍
查看>>
Directshow中的视频捕捉
查看>>
使用dbghelp生成dump文件以及事后调试分析
查看>>
vs2010编译ActiveX Control Test Container工具
查看>>
windows 内核函数前缀解析
查看>>
漫谈兼容内核之十二:Windows的APC机制
查看>>
ring0和ring3简介
查看>>
DllMain说明及如何获取DLL路径
查看>>
Detour开发包介绍(1):概述
查看>>
Detour开发包介绍(2):使用
查看>>
20.IDA-修改二进制文件、显示修改点
查看>>
Interview with Matt Pietrek - by Chris Maunder, 11 Sep 2000
查看>>
Linux下autoconf和automake使用
查看>>
Linux下Makefile快速编写入门
查看>>