[学习报告]《LeetCode零基础指南》(第九讲) 二级指针

x33g5p2x  于2021-11-30 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(280)

第一题:832. 翻转图像

第二题:867. 转置矩阵

第三题:566. 重塑矩阵

第四题2022. 将一维数组转变成二维数组

第一题:832. 翻转图像

  1. class Solution {
  2. public int[][] flipAndInvertImage(int[][] image) {
  3. int row=image.length;
  4. int col=image[0].length;
  5. int arr[][]=new int [row][col];
  6. for(int i=0;i<row;i++){
  7. for(int j=0;j<col;j++){
  8. arr[i][col-1-j]=image[i][j];
  9. }
  10. }
  11. for(int i=0;i<row;i++){
  12. for(int j=0;j<col;j++){
  13. if(arr[i][j]==1)arr[i][j]=0;
  14. else arr[i][j]=1;
  15. }
  16. }
  17. return arr;
  18. }
  19. }

 第二题:867. 转置矩阵

  1. class Solution {
  2. public int[][] transpose(int[][] matrix) {
  3. int row=matrix.length;
  4. int col=matrix[0].length;
  5. int arr[][]=new int[col][row];
  6. for(int i=0;i<row;i++){
  7. for(int j=0;j<col;j++){
  8. arr[j][i]=matrix[i][j];
  9. }
  10. }
  11. return arr;
  12. }
  13. }

 第三题:566. 重塑矩阵

  1. class Solution {
  2. public int[][] matrixReshape(int[][] mat, int r, int c) {
  3. //当此中不相等,这说明不存在,则返回原来的数组即可
  4. if(r*c!=mat.length*mat[0].length){return mat;}
  5. int arr[][]=new int [r][c];
  6. int m=0,n=0;
  7. for(int i=0;i<mat.length;i++){
  8. for(int j=0;j<mat[0].length;j++){
  9. arr[m][n++]=mat[i][j];
  10. if(n==c){//当达到指定列数时换行,累加的列清零。
  11. n=0;m++;
  12. }
  13. }
  14. }
  15. return arr;
  16. }
  17. }

第四题2022. 将一维数组转变成二维数组

  1. class Solution {
  2. public int[][] construct2DArray(int[] original, int m, int n) {
  3. //申明一个数组
  4. int res[][]={};
  5. if(m*n!=original.length)return res;
  6. // 创建一个动态开辟空间的数组
  7. int arr[][]=new int[m][n];//不能一开始就写这个,否则本当返回[],就会返回[[0]]
  8. int k=0;
  9. for(int i=0;i<m;i++){
  10. for(int j=0;j<n;j++){
  11. arr[i][j]=original[k++];
  12. if(k==original.length) break;
  13. }
  14. }
  15. return arr;
  16. }
  17. }

相关文章