Matrix Array旋转,输入flag 0 往左转,flag 1往右转
EX:{{1,2,3}, {4,5,6}} 1, return {{4,1}, {5,2}, {6,3}}
{{1,2,3}, {4,5,6}} 0, return {{3,6}, {2,5}, {1,4}}
基本双层Loop 下标变换一下搞定
leetcode 上就48,74,240算是有点相似,但也只是打基础,要会。
public static int[][] Solution(int[][] matrix, int flag) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return matrix;
//int m = matrix.length, n = matrix[0].length;
int[][] rvalue;
rvalue = transpose(matrix);
flip(rvalue, flag);
return rvalue;
}
private static int[][] transpose(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int[][] rvalue = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
rvalue[i][j] = matrix[j][i];
return rvalue;
}
private static void flip(int[][] matrix, int flag) {
int m = matrix.length, n = matrix[0].length;
if (flag == 1) { //clock wise
for (int i = 0; i < m; i++)
for (int j = 0; j < n / 2; j++) {
int temp=matrix[i][j];
matrix[i][j]=matrix[i][n-j-1];
matrix[i][n-j-1]=temp;
}
}
else {
for (int i = 0; i < m / 2; i++)
for (int j = 0; j < n; j++) {
int tmep= matrix[i][j];
matrix[i][j]=matrix[m-i-1][j];
matrix[m-i-1][j]=tmep;
}
}
}
- Search a 2D Matrix
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row=matrix.length;
int col=matrix[0].length;
int start=0,end=row*col-1;
while(start<=end){
int mid=(start+end)/2;
int mid_value=matrix[mid/col][mid%col];
if(mid_value==target) return true;
else if(mid_value>target) end=mid-1;
else start=mid+1;
}
return false;
}
}
- Search a 2D Matrix II
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row=0,col=matrix[0].length-1;
while(row<=matrix.length-1&&col>=0){
if(target==matrix[row][col]){
return true;
}else if(target>matrix[row][col]){
row++;
}else{
col--;
}
}
return false;
}
}