Skip to content

Latest commit

 

History

History
50 lines (42 loc) · 2.08 KB

739. Daily Temperatures.md

File metadata and controls

50 lines (42 loc) · 2.08 KB

Given a list of daily temperatures T, return a list such 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 of temperatures T = [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].

Solution

  • Java
    • mine

      LinkedList Runtime: 10 ms, faster than 92.87%, Memory Usage: 47 MB, less than 6.78% of Java online submissions

      same as 503. Next Greater Element II and 1019. Next Greater Node In Linked List

      //O(N)time O(N)space
      public int[] dailyTemperatures(int[] T) {
          int[] res = new int[T.length];
          LinkedList<Integer> list = new LinkedList<>();
          for(int i = 0; i < res.length; i++){
              while(!list.isEmpty() && T[list.peek()] < T[i]){
                  int t =  list.pop();
                  res[t] = i - t;
              }
              list.push(i);
          }
          return res;
      }
      
    • the most votes

      stack Runtime: 13 ms, faster than 80.57%, Memory Usage: 47.4 MB, less than 5.09% of Java online submissions

      //O(N)time O(N)space
      public int[] dailyTemperatures(int[] temperatures) {
          Stack<Integer> stack = new Stack<>();
          int[] ret = new int[temperatures.length];
          for(int i = 0; i < temperatures.length; i++) {
              while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                  int idx = stack.pop();
                  ret[idx] = i - idx;
              }
              stack.push(i);
          }
          return ret;
      }