48. Rotate Image

先按对角线对称图形,再水平对折。

class Solution {
public void rotate(int[][] matrix) {
//1.transpose
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < i; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//flip the matrix horizontally
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length / 2; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix[0].length - 1 -j];
matrix[i][matrix[0].length - 1 -j] = temp;
}
}
}
}

54. Spiral Matrix

从右到左,从下到上的时候,注意保证不重复。

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
return res;
int rowBegin = 0, rowEnd = matrix.length - 1, colBegin = 0, colEnd = matrix[0].length - 1;
while(rowBegin <= rowEnd && colBegin <= colEnd){
//to right
for(int j = colBegin; j <= colEnd; j++) res.add(matrix[rowBegin][j]);
rowBegin++; for(int i = rowBegin; i <= rowEnd; i++) res.add(matrix[i][colEnd]);
colEnd--; for(int j = colEnd; j >= colBegin && rowBegin <= rowEnd; j--) res.add(matrix[rowEnd][j]);
rowEnd--; for(int i = rowEnd; i >= rowBegin && colBegin <= colEnd; i--) res.add(matrix[i][colBegin]);
colBegin++;
}
return res;
}
}

59. Spiral Matrix II

规则的放入数字,不需要第三四步判断是否超出边界。

class Solution {
public int[][] generateMatrix(int n) {
if(n == 0)
return null;
int[][] matrix = new int[n][n];
int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1;
int count = 0;
while(rowBegin <= rowEnd && colBegin <= colEnd){
//right
for(int j = colBegin; j <= colEnd; j++)
matrix[rowBegin][j] = ++count;
rowBegin++; //down
for(int i = rowBegin; i <= rowEnd; i++)
matrix[i][colEnd] = ++count;
colEnd--; //left
for(int j = colEnd; j >= colBegin; j--)
matrix[rowEnd][j] = ++count;
rowEnd--; //up
for(int i = rowEnd; i >= rowBegin; i--)
matrix[i][colBegin] = ++count;
colBegin++;
}
return matrix;
}
}

最新文章

  1. (原创)使用VMware安装Ubuntu,怎么无法使用startx进入桌面模式?
  2. Bool 类型变量的使用
  3. C++浅析——继承类中构造和析构顺序
  4. jquery select选中表单特效三级联动
  5. [转载] Docker网络原则入门:EXPOSE,-p,-P,-link
  6. Linux命令之nslookup
  7. HDU 1158 Employment Planning (DP)
  8. Swift小功能点积累
  9. linux fdisk
  10. 前端开发 Grunt 之 Connect详解
  11. 新概念英语(1-3)Sorry, sir
  12. python的pandas库学习笔记
  13. redis-cli显示中文
  14. java_24.1文件流的应用--复制文件
  15. asp.net mvc easyui tree
  16. JAVA 设计模式遵循的六大基本准则
  17. API(一)之Serialization
  18. 常用jqueryPlugin
  19. ehcache.xml的配置详解和示例
  20. python获取前几天的时间

热门文章

  1. 性能对比:aelf智能合约运行环境性能是evm的1000倍
  2. Linux高性能服务器编程,书中的 shell 命令
  3. 阿里云 .NET SDK Roa 和 Rpc 风格签名
  4. F#周报2019年第24期
  5. C# 使用Environment获取当前程序运行环境相关信息
  6. C# if-else 语句
  7. 我脑中的JVM大全附带Java8的特性
  8. 玄学 npm报错记录
  9. block注意事项
  10. testlink 1.9.19安装