模拟
# 8. 字符串转换整数 (atoi) - 力扣(LeetCode) (opens new window)
class Solution {
public int myAtoi(String s) {
if (s == null || s.isEmpty()) return 0;
int index = 0, sign = 1;
long num = 0;
// 1. 跳过前导空格
while (index < s.length() && s.charAt(index) == ' ') index++;
if (index == s.length()) return 0;
// 2. 处理符号
if (s.charAt(index) == '+' || s.charAt(index) == '-') {
sign = (s.charAt(index) == '-') ? -1 : 1;
index++;
}
// 3. 转换数字
while (index < s.length() && Character.isDigit(s.charAt(index))) {
int digit = s.charAt(index) - '0';
num = num * 10 + digit;
// 4. 溢出检查
if (num * sign > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (num * sign < Integer.MIN_VALUE) return Integer.MIN_VALUE;
index++;
}
return (int)num * sign;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 54. 螺旋矩阵 - 力扣(LeetCode) (opens new window)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0)
return new ArrayList<Integer>();
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
int x = 0;
// 结果数组大小计算保持不变
Integer[] res = new Integer[(right + 1) * (bottom + 1)];
while (true) {
// 1. 从左向右遍历顶行
for (int i = left; i <= right; i++) {
res[x++] = matrix[top][i];
}
if (++top > bottom) break;
// 2. 从上向下遍历右列
for(int i = top; i <= bottom; i++) {
res[x++] = matrix[i][right];
}
if (--right < left) break;
// 3. 从右向左遍历底行
for (int i = right; i >= left; i--) {
res[x++] = matrix[bottom][i];
}
if (--bottom < top) break;
// 4. 从下向上遍历左列
for (int i = bottom; i >= top; i--) {
res[x++] = matrix[i][left];
}
if (++left > right) break;
}
return Arrays.asList(res);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
编辑 (opens new window)
上次更新: 2025/07/16, 10:21:39