每日溫度,華為高頻面試題

每日溫度,華為高頻面試題

最容易想到的是兩次for 迴圈,暴力解法。

遇到溫度高的就返回下標差,然後退出內迴圈,進入下一個外迴圈。

class Solution { public int[] dailyTemperatures(int[] temperatures) { int[] res = new int[temperatures。length]; for(int i = 0; i < temperatures。length; i++){ for(int j = i; j < temperatures。length; j++){//j 從 i 開始, 從當前天開始往後數 if(temperatures[j] > temperatures[i]){ int id = j - i; res[i] = id; break; }else{ res[i] = 0; } } } res[temperatures。length - 1] = 0; return res; }

class Solution { public int[] dailyTemperatures(int[] T) { Stack stack = new Stack<>(); int[] res = new int[T。length]; for(int i =0 ; i < T。length; i++){ //重複比較,棧頂有元素就要比較 while(!stack。isEmpty() && T[i] > T[stack。peek()]){ int k = stack。pop(); res[k] = i - k;//結果存入的索引差 } stack。push(i);//棧存入的是索引。 } return res; }}

解法2。用棧,棧儲存陣列元素的索引。

往棧裡壓入索引。stack。push(i)

棧不為空,就進行比較。如果比棧頂元素大T[i] > T[stack。peek()],就返回索引的差,存入結果陣列。

int k = stack。pop();

res[k] = i - k;//結果存入的索引差

每日溫度,華為高頻面試題

每日溫度,華為高頻面試題

dfs 走的路徑,有八個方向。因為除了自己,可以選擇9宮格的其他八個。

別的網格題目,一般是四個方向,上下左右便利。

題目意思:如果是b, 要遞迴的點選b 周圍8個, 如果是1, 說明周圍8個有一個地雷,這時候不需要遞迴點選周圍。如果點選到了地雷,把m 設定為x。

按照題目要求一步步模擬出掃雷

class Solution { // 定義 8 個方向 // int[] dx = {-1, 1, 0, 0, -1, 1, -1, 1}; // int[] dy = {0, 0, -1, 1, -1, 1, 1, -1}; int[][] direciton = new int[][]{{0, 1}, {0, -1}, {1, 1}, {1, 0}, {1, -1}, {-1, 1}, {-1, 0}, {-1, -1}}; public char[][] updateBoard(char[][] board, int[] click) { int x = click[0], y = click[1]; dfs(board, x, y); return board; } private void dfs(char[][] board, int x, int y) { // 遞迴終止條件:判斷空地 (i, j) 周圍是否有雷,若有,則將該位置修改為雷數,終止該路徑的搜尋。 if(x < 0 || x >= board。length || y < 0 || y >= board[0]。length){ return;//邊界 } // 有雷 if (board[x][y] == ‘M’) { board[x][y] = ‘X’; return;//結束 } if (board[x][y] == ‘E’) { countHole(board, x, y);//計算有地雷,改成相應的數字 if(board[x][y] == ‘B’){//附件無地雷 //遞迴掃雷 // 若空地 (x, y) 周圍沒有雷,則將該位置修改為 ‘B’,向 8 鄰域的空地繼續搜尋。 for(int i = 0; i < direciton。length; i++){ int newX = direciton[i][0] + x; int newY= direciton[i][1] + y; dfs(board, newX, newY);//遞迴掃雷 } } } } //計算地雷,改成相應的數字 private void countHole(char[][] board, int x, int y){ int count = 0; for(int i = 0; i < direciton。length; i++){ int newX = direciton[i][0] + x; int newY= direciton[i][1] + y; if(newX < 0 || newX >= board。length || newY < 0 || newY >= board[0]。length){ continue;//邊界 } if(board[newX][newY] == ‘M’){ count++; } } if(count == 0){ board[x][y] = ‘B’; }else{ board[x][y] = (char) (‘0’ + count);//計算地雷,改成相應的數字 } }}