# 数据结构与算法---螺旋矩阵、整数反转

## 螺旋矩阵

54. 螺旋矩阵

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]


[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]


### 思路

top、bottom、left、right

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if(matrix == null) return null;
List<Integer> array = new ArrayList<>();
if(matrix.length == 0) return array;
if(matrix[0].length == 0) return array;

int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;

while(left <= right && top <= bottom){
for(int i = left; i<=right; i++){
array.add(matrix[top][i]);
}
top++;
if(left > right || top > bottom) break;

for(int i = top; i<=bottom; i++){
array.add(matrix[i][right]);
}
right--;
if(left > right || top > bottom) break;

for(int i = right; i>=left; i--){
array.add(matrix[bottom][i]);
}
bottom--;
if(left > right || top > bottom) break;

for(int i = bottom; i>=top; i--){
array.add(matrix[i][left]);
}
left++;
if(left > right || top > bottom) break;
}
return array;
}
}


## 整数反转

7. 整数反转

### 思路

1234
1234 % 10 = 4得到个位数4
1234 / 10 = 123得到剩余的数
123 % 10 = 3得到个位数
result = (((4 * 10) + 3) * 10 + 2) * 10 + 1
result = 4000 + 300 + 20 + 1 = 4321

class Solution {
public int reverse(int x) {
long result = 0;
while(x != 0){
result = result * 10 + x % 10;
if(result > Integer.MAX_VALUE) return 0;
if(result < Integer.MIN_VALUE) return 0;
x = x/10;
}
return (int)result;
}
}


class Solution {
public int reverse(int x) {
int result = 0;
while(x != 0){
int pre = result;
result = pre * 10 + x % 10;
if((result - x % 10)/10 != pre) return 0;
x = x/10;
}
return result;
}
}


08-26 2832

10-01 1713
12-12 248
06-03 5280
04-19 177
08-16 540
07-11 228
04-13 358
12-13 159
09-14 161
03-12 130
04-04 103
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客