59.螺旋矩陣II
題目
給你一個正整數?n
?,生成一個包含?1
?到?n2
?所有元素,且元素按順時針順序螺旋排列的?n x n
?正方形矩陣?matrix
?。
示例 1:
輸入:n = 3 輸出:[[1,2,3],[8,9,4],[7,6,5]]
代碼(新解法)
class Solution {public int[][] generateMatrix(int n) {int left = 0;int right = n - 1;int up = 0;int down = n - 1;int count = 1;int[][] matrix = new int[n][n];while(count <= n*n){for(int i=left;i <= right;i++){matrix[up][i] = count++;}up++;for(int i=up;i <= down;i++){matrix[i][right] = count++;}right--;for(int i=right;i >= left;i--){matrix[down][i] = count++;}down--;for(int i=down;i >= up;i--){matrix[i][left] = count++;}left++;}return matrix;}
}
54.螺旋矩陣
題目
給你一個?m
?行?n
?列的矩陣?matrix
?,請按照?順時針螺旋順序?,返回矩陣中的所有元素。
示例 1:
輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 輸出:[1,2,3,6,9,8,7,4,5]
代碼(解法同上面的59)
class Solution {public List<Integer> spiralOrder(int[][] matrix) {int left = 0;int right = matrix[0].length - 1;int top = 0;int bottom = matrix.length - 1;List<Integer> list = new ArrayList<>();int count = 1;int all = matrix[0].length * matrix.length;//count <= all要加上,因為4個for循環是一起執行完才判斷while條件的//如果不加這個判斷,不然最后可能會多幾個數(多執行了for)while(count <= all){for(int i=left; i <= right && count <= all; i++){list.add(matrix[top][i]);count++;}top++;for(int i=top; i <= bottom && count <= all; i++){list.add(matrix[i][right]);count++;}right--;for(int i=right; i >= left && count <= all; i--){list.add(matrix[bottom][i]);count++;}bottom--;for(int i=bottom; i >= top && count <= all; i--){list.add(matrix[i][left]);count++;}left++;}return list;}
}
LCR146.螺旋遍歷二維數組
題目
給定一個二維數組?array
,請返回「螺旋遍歷」該數組的結果。
螺旋遍歷:從左上角開始,按照?向右、向下、向左、向上?的順序?依次?提取元素,然后再進入內部一層重復相同的步驟,直到提取完所有元素。
示例 1:
輸入:array = [[1,2,3],[8,9,4],[7,6,5]] 輸出:[1,2,3,4,5,6,7,8,9]
代碼(原理同54,修改了一點點)
class Solution {public int[] spiralArray(int[][] array) {//這個必須要寫,不然array為空時,array[0]會報錯if(array.length == 0) {return new int[0];}int left = 0;int right = array[0].length - 1;int top = 0;int bottom = array.length - 1;int[] res = new int[array[0].length * array.length];int count = 0;int all = array[0].length * array.length;//count < all要加上,因為4個for循環是一起執行完才判斷while條件的//如果不加這個判斷,不然最后可能會多幾個數(多執行了for)while(count < all){for(int i=left; i <= right && count < all; i++){res[count++] = array[top][i];}top++;for(int i=top; i <= bottom && count < all; i++){res[count++] = array[i][right];}right--;for(int i=right; i >= left && count < all; i--){res[count++] = array[bottom][i];}bottom--;for(int i=bottom; i >= top && count < all; i--){res[count++] = array[i][left];}left++;}return res;}
}