每日温度
压入栈时的元素和栈内的元素比较,有三个情况,栈内元素大于等于压入栈时的元素,此时压入栈内;如果小于压入栈内的元素,先记录result,再在栈中弹出元素,一直循环,直到大于等于压入栈时的元素,才压入栈内。
- public class Solution {
- public int[] DailyTemperatures(int[] temperatures) {
- int[] result = new int[temperatures.Length];
- Stack<int> stack = new Stack<int>();
- stack.Push(0);
-
- for(int i=1;i
- if(temperatures[i] < temperatures[stack.Peek()]){
- stack.Push(i);
- }else if(temperatures[i] == temperatures[stack.Peek()]){
- stack.Push(i);
- }else{
- while (stack.Count > 0 && temperatures[i] > temperatures[stack.Peek()]) {
- result[stack.Peek()] = i - stack.Peek();
- stack.Pop();
- }
- stack.Push(i);
- }
- }
- return result;
- }
- }
下一个更大元素 I
- public class Solution {
- public int[] NextGreaterElement(int[] nums1, int[] nums2) {
- Stack<int> stack = new Stack<int>();
- Dictionary<int, int> map = new Dictionary<int, int>();
- 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;
- }
- }