1. 程式人生 > >每日溫度

每日溫度

根據每日 氣溫 列表,請重新生成一個列表,對應位置的輸入是你需要再等待多久溫度才會升高的天數。如果之後都不會升高,請輸入 0 來代替。

例如,給定一個列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的輸出應該是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:氣溫 列表長度的範圍是 [1, 30000]。每個氣溫的值的都是 [30, 100] 範圍內的整數。

 

思路:

1.首先想到暴力比較:兩層for迴圈

//暴力比較 O(n^2)
	public static int[] dailyTemperatures(int[] T) {
		int[] res = new int[T.length];
		res[res.length - 1] = 0;
		for (int i = 0; i < res.length - 1; i++) {
			for (int j = i + 1; j < res.length; j++) {
				if (T[j] > T[i]) {
					res[i] = j - i;
					break;
				} else if (j == res.length - 1) {
						res[i] = 0;
					}
				
			}
		}
		return res;
	}

時間複雜度較大

2.用棧儲存陣列下標,每次彈出下標  找到第一個比該下標對應元素大的位置

        //用一個棧儲存陣列的下標   O(n)
		public static int[] dailyTemperatures(int[] T) {
			Stack<Integer> stack =new Stack<>();  //儲存陣列下標
			int[] res = new int[T.length];
			Arrays.fill(res, 0);
			for (int i = 0; i < res.length; i++) {
				while (!stack.isEmpty()&&T[i]>T[stack.peek()]) {
					int resIndex=stack.pop();
					res[resIndex]=i-resIndex;
				}
				//每次進來都把下標儲存
				stack.push(i);
			}
			return res;
		}