LC.P1706[球会落何处]

方法一:模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[] findBall(int[][] grid) {
int n = grid[0].length;
int[] ans = new int[n];
for (int j = 0; j < n; ++j) {
int col = j;
for (int[] row : grid) {
int point = row[col];
col += point; // 移动
if (col < 0 || col == n || row[col] != point) {
col = -1;
break;
}
}
ans[j] = col;
}
return ans;
}
}
  • 时间复杂度:$O(mn)$
  • 空间复杂度:$O(n)$