zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
    埋骨何须桑梓地,人生无处不青山
  • 相关阅读:
    require() 源码解读
    那些JS容易忽略的题
    javascript:void(0);与return false
    location.href
    IE CSS Bugs 列表和解决方法
    npm 常用命令
    移动开发不能不知道的事-meta
    Canvas介绍
    用CSS变形创建圆形导航
    一个传统行业互联网系统的架构演化(Week 4)
  • 原文地址:https://www.cnblogs.com/ACMerszl/p/15468452.html
Copyright © 2011-2022 走看看