单调栈的应用(用于解决NextGreaterElement问题)

题一:返回下一个更大元素

/**
 * 单调栈的使用
 * 下一个更大元素
 *
 * @param nums1
 * @param nums2
 * @return
 */
public int[] nextGreaterElement(int nums1[], int nums2[]) {
    
    
    int result[] = new int[nums1.length];
    Deque<Integer> stack = new LinkedList<>();
    // HashMap辅助存储当前元素(key)与下一个更大元素(value)
    HashMap<Integer, Integer> hashMap = new HashMap<>();
    for (int i = 0; i < nums2.length; i++) {
    
    
        while (!stack.isEmpty() && nums2[i] > stack.peek()) {
    
    
            hashMap.put(stack.pop(), nums2[i]);
        }
        stack.push(nums2[i]);
    }
    while (!stack.isEmpty()) {
    
    
        hashMap.put(stack.pop(), -1);
    }
    for (int i = 0; i < nums1.length; i++) {
    
    
        result[i] = hashMap.get(nums1[i]);
    }
    return result;
}

题二:返回下一个更大元素距离当前位置的距离

public int[] dailyTemperatures(int[] T) {
    
    
    int[] ans = new int[T.length]; // 用于返回结果
    // 如果一个下标在单调栈里,则表示尚未找到下一次温度更高的下标。
    Deque<Integer> stack = new LinkedList<Integer>(); // 用于存储下标的单调栈
    for (int i = 0; i < T.length; i++) {
    
    
        while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
    
     // 符合条件
            int prevIndex = stack.pop();
            ans[prevIndex] = i - prevIndex;
        }
        stack.push(i);
    }
    return ans;
}

猜你喜欢

转载自blog.csdn.net/for62/article/details/108572395