一、顺时针打印矩阵
宏观的将整个矩阵看作是一个套一个的方框 ,找到对角线上两个点的坐标,遍历每一个方框。
public static void method(int[][] arr) {
method2(arr, 0, 0, arr.length - 1, arr[0].length - 1);
}
public static void method2(int[][] arr, int tr1, int td1, int tr2, int td2) {
if (tr1 > tr2 || td1 > td2) {
return;
}
int tr = tr1;
int td = td1;
if (tr1 == tr2) {
while (td <= td2) {
System.out.println(arr[tr][td++]);
}
return;
}
if (td1 == td2) {
while (tr <= tr2) {
System.out.println(arr[tr++][td]);
}
return;
}
while (td < td2) {
System.out.println(arr[tr][td++]);
}
while (tr < tr2) {
System.out.println(arr[tr++][td]);
}
while (td > td1) {
System.out.println(arr[tr][td--]);
}
while (tr > tr1) {
System.out.println(arr[tr--][td]);
}
method2(arr, tr1 + 1, td1 + 1, tr2 - 1, td2 - 1);
}
二、逆时针旋转矩阵,要求空间复杂度O(1)
将每个方框的每一行与其对应列的相应位置交换
public static void method(int[][] arr) {
method2(arr, 0, 0, arr.length - 1, arr.length - 1);
}
public static void method2(int[][] arr, int tr1, int td1, int tr2, int td2) {
if (tr1 >= tr2) {
return;
}
for (int i = 0; i < tr2 - tr1; i++) {
int temp = arr[tr1][td1 + i];
arr[tr1][td1 + i] = arr[tr1 + i][td2];
arr[tr1 + i][td2] = arr[tr2][td2 - i];
arr[tr2][td2 - i] = arr[tr2 - i][td1];
arr[tr2 - i][td1] = temp;
}
method2(arr, tr1 + 1, td1 + 1, tr2 - 1, td2 - 1);
}
三、“之”字形打印矩阵,要求空间复杂度O(1)
private static void method(int[][] arr) {
int tr1 = 0, td1 = 0, tr2 = 0, td2 = 0;
while (td1 < arr[0].length) {
print(arr, tr1, td1, tr2);
if (tr1 == arr.length - 1) {
td1++;
} else {
tr1++;
}
if (td2 == arr[0].length - 1) {
tr2++;
} else {
td2++;
}
}
}
private static void print(int[][] arr, int tr1, int td1, int tr2) {
int tr = tr1, td = td1;
while (tr >= tr2) {
System.out.println(arr[tr][td]);
tr--;
td++;
}
}
四、在一个行和列都有顺序的矩阵(n+m)中查找某一个数,要求时间复杂度O(n+m)。
从右上角开始查找,大于目标就左移,小于目标就下移,直到左下角。
private static boolean method(int[][] arr, int target) {
int tr = 0, td = arr[0].length - 1;
while (tr != arr.length && td != -1) {
if (arr[tr][td] > target) {
td--;
} else if (arr[tr][td] < target) {
tr++;
} else {
return true;
}
}
return false;
}