标签:
details kill
public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> res = new ArrayList<Integer>(); if(matrix==null || matrix.length==0 || matrix[0].length==0) return res; int bottom=matrix.length-1, top=0, left=0, right = matrix[0].length-1; while(left<right && top<bottom){ for(int i=left;i<right;i++){ res.add(matrix[top][i]); } for(int j=top;j<bottom;j++){ res.add(matrix[j][right]); } for(int i=right;i>left;i--){ res.add(matrix[bottom][i]); } for(int j=bottom;j>top;j--){ res.add(matrix[j][left]); } right--; left++; top++; bottom--; } if(left==right){ for(int i=top; i<=bottom; i++) res.add(matrix[i][left]); }else if(top==bottom){ // must be "else if" not "if" for(int j=left;j<=right;j++) res.add(matrix[top][j]); } return res; } }
II
public class Solution { public int[][] generateMatrix(int n) { if(n<0) return null; int[][] res = new int[n][n]; int r=n-1, l=0, t=0, b=n-1; int k=1; while(l<r){ for(int i=l; i<r; i++){ res[t][i] = k++; } for(int i=t; i<b; i++){ res[i][r] = k++; } for(int i=r; i>l; i--){ res[b][i] = k++; } for(int i=b; i>t; i--){ res[i][l] = k++; } l++; r--; b--; t++; } if(n%2==1) res[(int) n/2][(int) n/2] = k++; return res; } }
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4424540.html