zoukankan      html  css  js  c++  java
  • 下一个更大元素 I

    这道题不是循环数组用的是栈存储的是数组的值不是下标,如果是循环数组用值会出现无法确定结果要赋值到哪个位置

    class Solution {
        public int[] nextGreaterElement(int[] nums1, int[] nums2) {
            //不是循环数组
            int[] res = new int[nums1.length];
            Stack<Integer> stk = new Stack<>();
            HashMap<Integer,Integer> hash = new HashMap<>();
            for(int i=0;i<nums2.length;i++){
                while(!stk.isEmpty() && nums2[i] > stk.peek()){
                    hash.put(stk.pop(),nums2[i]);
                }
                stk.add(nums2[i]);
            }
            int top = 0;
            for(int num:nums1){
                if(hash.containsKey(num)){
                    res[top++] = hash.get(num);
                }else{
                     res[top++] = -1;
                }
            }
            return res;
        }
    }
    
    

  • 相关阅读:
    LeetCode "Sum Root to Leaf Numbers"
    LeetCode "Single Number"
    POJ #1033
    POJ #1011
    POJ #2411
    POJ #1276
    POJ #1260
    POJ #1221
    POJ #1080
    POJ #1050
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13423219.html
Copyright © 2011-2022 走看看