LeetCode--Next Greater Element

LeetCode–Next Greater Element

原题如下:

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.


一开始,我看题也看蒙圈了。通过演练代码和仔细阅读,理解大致如下:

给出两个不重复数组,数组1就是数组2的子集,换句话说就是数组1是数组2的真子集,找出所有数组1中元素在数组2中相应位置往右第一个比该元素大的元素,如果没有对应的输出-1。说起来很绕。

举个例子:
数组A:[3,4]
数组B:[3,1,2,4]

数组A中的第一个元素3,对应到数组B中的3,数组B中的3右侧第一个大于3的元素就是4,所以数组A中的3对应输出4。

数组A中的第二个元素4,对应到数组B的4,4右侧已无元素,所以数组A中的4对应输出-1.

输出应该为[4,-1]

思路:

  1. 遍历数组B中元素,先将数组B中的第一个元素推入栈中称为栈顶元素,然后让紧邻的下一个元素与栈顶元素比较,如果栈顶元素大于该元素,则继续讲该元素推入栈中,成为新的栈顶元素,如果栈顶元素小于该元素,则以(栈顶元素,该元素)键值对的形式存到HashMap中,并将该元素推入栈中称为新的栈顶元素。循环此操作
  2. 遍历数组A中的值与HashMap中的键一一比较,如果存在,则返回值,如果不存在则返回-1。

亲测,正常运行代码:

package com.zpy.nextgreaterelement;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class nextGreaterElement {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        nextGreaterElement n = new nextGreaterElement();
        int[] findNums = new int[] {4,1,2};
        int[] nums = new int[] {1,3,4,2};
        int[] result = n.findGreater(findNums, nums);
        for (int i : result) {
            System.out.println(i);
        }
    }
    //实现方法如下
    public int[] findGreater(int findNums[],int nums[])
    {
        Map<Integer, Integer> map = new HashMap<>();
        Stack<Integer> stack = new Stack<>();
        for (int num : nums) {
            while(!stack.isEmpty()&&stack.peek()<num){
                map.put(stack.pop(), num);
            }
            stack.push(num);
        }
        for(int i = 0;i<findNums.length;i++){
            findNums[i] = map.getOrDefault(findNums[i], -1);
        }
        return findNums;
    }
}

Output:
-1
3
-1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值