栈-E496-下一个更大元素I

2019-03-21  本文已影响0人  三次元蚂蚁

题目

思路

  1. a < b => aplus = b
  2. a > b && bplus == -1 => aplus = -1
  3. a > b && a < bplus => aplus = bplus
  4. a > b && a > bplus => b = bplus,继续应用该规律

特别注意:继续应用该规律时,bplus也要相对应地更新

代码

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] result = new int[nums1.length];
        Map<Integer, Integer> map = new HashMap<>();
        
        if (nums2.length == 0) {
            return result;
        }
        map.put(nums2[nums2.length - 1], -1);
        
        //aplus should be init because it doesn't evaluated in every branch
        int a, b, aplus = -1, bplus;
        boolean flag;
        for (int i = nums2.length - 2; i >= 0; i--) {
            a = nums2[i];
            b = nums2[i + 1];
            
            do {
                flag = false; //move the flag into while block for modifying flag in each branch
                bplus = map.get(b); //move the bplus into while block for matching up the change of b
                if (a < b) {
                    aplus = b;
                } else {
                    if (bplus == -1) {
                        aplus = -1;
                    } else if (a < bplus) {
                        aplus = bplus;
                    } else {
                        b = bplus;
                        flag = true;
                    }
                }
            } while (flag);
            
            map.put(a, aplus);
        }
        
        for (int i = 0; i < nums1.length; ++i) {
            result[i] = map.get(nums1[i]);
        }
        return result;
    }
}
上一篇下一篇

猜你喜欢

热点阅读