此类题目就是花式遍历2维数组,我个人并不喜欢。
498. Diagonal Traverse
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
Approach #1 抄大神的解法
public class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) return new int[0];
int m = matrix.length, n = matrix[0].length;
int[] result = new int[m * n];
int row = 0, col = 0, d = 1;
for (int i = 0; i < m * n; i++) {
result[i] = matrix[row][col];
row -= d;
col += d;
if (row >= m) { row = m - 1; col += 2; d = -d;}
if (col >= n) { col = n - 1; row += 2; d = -d;}
if (row < 0) { row = 0; d = -d;}
if (col < 0) { col = 0; d = -d;}
}
return result;
}
}
Approach #2
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return new int[0];
int m = matrix.length, n = matrix[0].length;
int[] r = new int[m * n];
for(int i = 0, p = 0; i < m + n - 1; i++) {
if(i % 2 == 0) {
for(int j = Math.max(0, i+1-m); j < Math.min(n, i + 1); j++) {
r[p++] = matrix[i-j][j];
}
} else {
for(int j = Math.min(n-1, i); j >= Math.max(0, i+1-m); j--) {
r[p++] = matrix[i-j][j];
}
}
}
return r;
}
}
54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Approach #1
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
for(int i = 0 ; i < numRows; i++) {
List<Integer> list = new ArrayList<>();
for(int j = 0; j < i + 1 ; j++) {
if(j == 0 || j == i) {
list.add(1);
}
else {
int a = result.get(i - 1).get(j - 1);
int b = result.get(i - 1).get(j);
list.add(a + b);
}
}
result.add(list);
}
return result;
}
}
118. Pascal's Triangle
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
Approach #1
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> row, pre = null;
for (int i = 0; i < numRows; ++i) {
row = new ArrayList<Integer>();
for (int j = 0; j <= i; ++j)
if (j == 0 || j == i)
row.add(1);
else
row.add(pre.get(j - 1) + pre.get(j));
pre = row;
res.add(row);
}
return res;
}
}
分析:
对于杨辉三角,观察找规律。
1. 第i行有i个元素
2. 每一行首位row[0] 和末位 row[len-1]都是1
3. 对于行i>2的非首尾元素,a[i][j] = a[i-1][j-1]+a[i-1][j]