1.旋转矩阵
题目: https://www.jianshu.com/p/add62418ee0a
demo:
public static void rotate(int[][] arr) {
int length = arr.length;
int[][] newArr = new int[length][length];
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
newArr[j][length - i - 1] = arr[i][j];
}
}
for (int i = 0; i < length; i++) {
arr[i] = Arrays.copyOf(newArr[i], length);
}
}
测试:
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
rotate(arr);
for (int[] ints : arr) {
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
}
2.零矩阵
题目:https://leetcode-cn.com/problems/set-matrix-zeroes/
demo:
/**
* 思路:将行和列的0分别找出来并记录
*/
public static void setZero(int[][] arr) {
int colLength = arr.length;
int lineLength = arr[0].length;
int totalLength = colLength * lineLength;
int[] col = new int[totalLength];
int[] line = new int[totalLength];
int colIndex = 0;
int lineIndex = 0;
for (int i = 0; i < colLength; i++) {
for (int j = 0; j < lineLength; j++) {
if (arr[i][j] == 0) {
// 因为int数组默认值为0,所以为了防止混乱,将记录的行和罗列的索引位置加1
col[colIndex] = j + 1;
line[lineIndex] = i + 1;
colIndex++;
lineIndex++;
}
}
}
// 将列设置成0
for (int i : col) {
if (i == 0) {
continue;
}
for (int j = 0; j < colLength; j++) {
arr[j][i - 1] = 0;
}
}
// 将行设置成0
for (int i : line) {
if (i == 0) {
continue;
}
for (int j = 0; j < lineLength; j++) {
arr[i - 1][j] = 0;
}
}
}
测试:
public static void main(String[] args) {
int[][] arr = {{0, 0, 0, 5}, {4, 1, 6, 1}, {0, 1, 6, 1}, {4, 1, 6, 1}, {0, 0, 6, 1}};
setZero(arr);
for (int[] ints : arr) {
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
}
3.对角线遍历
题目: https://leetcode-cn.com/problems/diagonal-traverse/
/**
* 思路:总查找次数=行长度+列长度-1
* 次数为偶数时,行坐标减,列坐标加
*/
public static int[] find(int[][] arr) {
int lineLength = arr.length;
int colLength = arr[0].length;
int[] newArr = new int[lineLength * colLength];
int newIndex = 0;
for (int i = 0; i < lineLength + colLength - 1; i++) {
// 确定最大的横坐标,最大的纵坐标值
int maxLI = Math.min(i, lineLength - 1);
int maxCI = Math.min(i, colLength - 1);
// 确定最小的横坐标值,最小的纵坐标
int minLI = Math.max(0, i - maxCI);
int minCI = Math.max(0, i - maxLI);
// 算出来的横坐标,纵坐标的最大值和最小值差都相等
int diff = maxLI - minLI;
for (int j = 0; j <= diff; j++) {
// 偶数时,横坐标减
if (i % 2 == 0) {
newArr[newIndex] = arr[maxLI - j][minCI + j];
} else {
newArr[newIndex] = arr[minLI + j][maxCI - j];
}
newIndex++;
}
}
return newArr;
}
测试:
public static void main(String[] args) {
int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int[] ints = find(arr);
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
}
4.文章参考链接
a.https://www.jianshu.com/p/add62418ee0a
b.https://leetcode-cn.com/problems/set-matrix-zeroes/
c.https://leetcode-cn.com/problems/diagonal-traverse/