标签:break star 清除 src item solution int com bre
第一次循环
[ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12],
[13,14,15,16]
]
第二次循环就变成
[
[6,7],
[10,11]
]
当下一次循环的时候 ,数组变成长度为1直接add到list即可。无需循环
解:
class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> list = new ArrayList(); if (matrix.length == 0) { return list; } int len = Arrays.stream(matrix).mapToInt(arr -> arr.length).sum(); //循环** /** * [1, 2, 3, 4], * * [5, 6, 7, 8], * * [9,10,11,12], * * [13,14,15,16] * {17,18,19,20} * */ while (len != list.size()) { int[] arr = matrix[0]; if(matrix.length == 1) { for(int i = 0 ; i < matrix.length ; i ++) { int [] arrs = matrix[i]; Arrays.stream(arrs).forEach(item->{ list.add(item); }); } break; } for(int i = 0 ; i < matrix.length; i ++) { int [] arrs = matrix[i]; if(arrs.length == 1) { list.add(arrs[0]); } } if(list.size() == len) { break; } int [][] newArr = new int[matrix.length-1][]; //第一次横排 for (int k = 0; k < arr.length; k++) { list.add(arr[k]); } for(int i = 0 ; i < newArr.length; i ++) { newArr[i] = matrix[i+1]; } //第一次纵排 for(int y = 0 ; y < matrix.length ; y ++ ) { int [] colArr = matrix[y]; if(y == 0) { continue; } list.add(colArr[colArr.length-1]); } int [][] newArr1 = new int [newArr.length][]; for(int i = 0 ; i < newArr.length; i ++ ) { int [] horArr = new int[newArr[0].length-1]; for(int k = 0 ; k < horArr.length ; k ++ ) { horArr[k] = newArr[i][k]; } newArr1[i] = horArr; } //第二次横排 int [] lastArr = matrix[matrix.length-1]; for(int z = lastArr.length - 1 ; z >= 0 ; z--) { if(z == lastArr.length - 1) { continue; } list.add(lastArr[z]); } int [][] newArr2 = new int [newArr1.length-1][]; for(int z = 0 ; z < newArr1.length - 1 ; z++) { int [] arr2 = newArr1[z]; newArr2[z] = arr2; } //第二次纵排 for(int i = matrix.length - 1 ; i >= 0 ; i -- ) { int [] colArr = matrix[i]; if(i == 0 || i == matrix.length -1 ) { continue; } list.add(colArr[0]); } int [][] newArr3 = new int [newArr2.length][]; for(int i = 0 ; i < newArr3.length; i ++ ) { int [] horArr = new int[newArr2[0].length-1]; for(int k = 0 ; k < horArr.length ; k ++ ) { horArr[k] = newArr2[i][k+1]; } newArr3[i] = horArr; } matrix = newArr3 ; } return list; } }
标签:break star 清除 src item solution int com bre
原文地址:https://www.cnblogs.com/1-Admin/p/12150326.html