螺旋矩阵
54. 螺旋矩阵
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
思路
需要定义四个变量:
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;
}
}
整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
思路
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
关于溢出,可以使用long类型,然后返回的时候再强转为int
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;
}
}