代码随想录算法训练营|五十七天

每日温度

739. 每日温度 - 力扣(LeetCode)

压入栈时的元素和栈内的元素比较,有三个情况,栈内元素大于等于压入栈时的元素,此时压入栈内;如果小于压入栈内的元素,先记录result,再在栈中弹出元素,一直循环,直到大于等于压入栈时的元素,才压入栈内。

public class Solution {
    public int[] DailyTemperatures(int[] temperatures) {
        int[] result = new int[temperatures.Length];
        Stack stack = new Stack();
        stack.Push(0);

        for(int i=1;i 0 && temperatures[i] > temperatures[stack.Peek()]) {
                    result[stack.Peek()] = i - stack.Peek();
                    stack.Pop();
                }
                stack.Push(i);
            }
        }
        return result;
    }
}

下一个更大元素 I

496. 下一个更大元素 I - 力扣(LeetCode)

public class Solution {
    public int[] NextGreaterElement(int[] nums1, int[] nums2) {
        Stack stack = new Stack();
        Dictionary map = new Dictionary();
        int[] result = new int[nums1.Length];
        
        for (int i = 0; i < nums1.Length; i++) {
            map[nums1[i]] = i;
        }
        
        for (int i = 0; i < nums2.Length; i++) {
            while (stack.Count > 0 && nums2[i] > stack.Peek()) {
                int num = stack.Pop();
                if (map.ContainsKey(num)) {
                    result[map[num]] = nums2[i];
                }
            }
            stack.Push(nums2[i]);
        }
        
        while (stack.Count > 0) {
            int num = stack.Pop();
            if (map.ContainsKey(num)) {
                result[map[num]] = -1;
            }
        }
        
        return result;
    }
}

你可能感兴趣的:(代码随想录,算法,leetcode)