博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - 496 Next Greater Element I
阅读量:5815 次
发布时间:2019-06-18

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

问题

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].Output: [-1,3,-1]Explanation:    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.    For number 1 in the first array, the next greater number for it in the second array is 3.    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

思路

提交

beats 79.78%

public class Solution {    public int[] nextGreaterElement(int[] findNums, int[] nums) {        if (nums == null || nums.length == 0) {            return new int[]{};        }        HashMap
map = new HashMap<>(); int numsLength = nums.length; map.put(nums[numsLength - 1], -1); for (int i = numsLength - 2; i >= 0; i--) { if (nums[i] < nums[i + 1]) { map.put(nums[i], nums[i + 1]); } else { int j = i + 1; while (j < numsLength && nums[i] > nums[j]) { j++; } if (j == numsLength) { map.put(nums[i], -1); } else { map.put(nums[i], nums[j]); } } } int length = findNums.length; int[] result = new int[length]; for (int i = 0; i < length; i++) { result[i] = map.get(findNums[i]); } return result; }}

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

你可能感兴趣的文章
$_SERVER['SCRIPT_FLENAME']与__FILE__
查看>>
skynet实践(8)-接入websocket
查看>>
系统版本判断
查看>>
My97DatePicker 日历插件
查看>>
0603 学术诚信与职业道德
查看>>
小点心家族第3位成员——楼层定位效果
查看>>
Knockout.Js官网学习(enable绑定、disable绑定)
查看>>
hive基本操作与应用
查看>>
excel快捷键设置
查看>>
poj3692
查看>>
python之信号量【Semaphore】
查看>>
html5纲要,细谈HTML 5新增的元素
查看>>
Android应用集成支付宝接口的简化
查看>>
[分享]Ubuntu12.04安装基础教程(图文)
查看>>
#HTTP协议学习# (二)基本认证
查看>>
Android开发之线性布局详解(布局权重)
查看>>
WCF
查看>>
django 目录结构修改
查看>>
win8 关闭防火墙
查看>>
Android实例-录音与回放(播放MP3)(XE8+小米2)
查看>>