LeetCode 496. 下一个更大元素 I

传送门

Solution

思路1:

暴力

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] ans = new int[nums1.length];
        int cur = 0;
        for (int x: nums1) {
            boolean flag = false;
            boolean isOk = false;
            for (int y: nums2) {
                if (flag && y > x) {
                    ans[cur++] = y;
                    isOk = true;
                    break;
                } 
                if (y == x) flag = true;
            }
            if (isOk == false) ans[cur++] = -1;
        }
        return ans;
    }
}

思路2:

首先考虑因为要找右边的第一个比它大的数,所有从右边往左维护,就容易想到单调栈,遇到比自己小的就出栈,找到之前比自己大的第一个数,然后用Map映射一下。

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int n = nums1.length, m = nums2.length;
        Deque<Integer> stack = new ArrayDeque<Integer>();
        Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
        int[] ans = new int[n];
        for (int i = m - 1; i >= 0; i--) { 
            int x = nums2[i];
            while (!stack.isEmpty() && stack.peek() <= x) stack.pop();
            mp.put(x, stack.isEmpty() ? -1 : stack.peek());
            stack.push(x);           
        }              
        for (int i = 0; i < n; i++) {
            nums1[i] = mp.get(nums1[i]);
        }
        return nums1;
    }
}
posted @ 2021-10-26 23:19  Frontierone  阅读(19)  评论(0编辑  收藏  举报