739. Daily Temperatures 每日温度

 Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].


Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].


根据每日气温列表,制作一个列表,在输入的每一天中,都会告诉您需要等待多长时间,直到温度升高。如果没有这个可能的日子,那就把0代替。

例如,给定列表温度= [73,74,75,71,69,72,76,73],您的输出应该是[1,1,4,2,1,1,0,0]。
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Solution {
  6. public class Solution {
  7. public int[] DailyTemperatures(int[] temperatures) {
  8. int[] res = new int[temperatures.Length];
  9. Stack<int> stack = new Stack<int>();
  10. for(int i = 0; i < temperatures.Length; i++) {
  11. while(!(stack.Count() == 0) && temperatures[i] > temperatures[stack.Peek()]) {
  12. int idx = stack.Pop();
  13. res[idx] = i - idx;
  14. }
  15. stack.Push(i);
  16. }
  17. return res;
  18. }
  19. }
  20. public class Solution2 {
  21. public int[] DailyTemperatures(int[] temperatures) {
  22. int[] res = new int[temperatures.Length];
  23. Dictionary<int,int> dict = new Dictionary<int, int>();
  24. for(var i = temperatures.Length - 1; i >= 0; i--) {
  25. res[i] = Int32.MaxValue;
  26. foreach(int key in dict.Keys) {
  27. if (temperatures[i] < key) {
  28. res[i] = Math.Min(res[i], dict[key] - i);
  29. }
  30. }
  31. dict[temperatures[i]] = i;
  32. res[i] = res[i] == Int32.MaxValue ? 0 : res[i];
  33. }
  34. return res;
  35. }
  36. }
  37. class Program {
  38. static void Main(string[] args) {
  39. Solution s = new Solution();
  40. int[] arr = {73, 74, 75, 71, 69, 72, 76, 73};
  41. var res = s.DailyTemperatures(arr);
  42. Console.WriteLine(res);
  43. }
  44. }
  45. }






posted @ 2017-12-06 22:43  xiejunzhao  阅读(416)  评论(0编辑  收藏  举报