24.10.10
错误代码
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int st = s.length - 1;
int count = 0;
for(int i = g.length - 1; i >= 0; i--){
if (s[st] >= g[i] && st >= 0) {
st--;
count++;
}
}
return count;
}
}
报错原因:java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 0
边界检查:代码中,
if (s[st] >= g[i] && st >= 0)
的条件可能会导致在st小于0时访问s[st],这会引发ArrayIndexOutOfBoundsException。应该先检查st >= 0,再访问数组元素
应改为
if (st >= 0 && s[st] >= g[i])
最终正确代码
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int st = s.length - 1;
int count = 0;
for(int i = g.length - 1; i >= 0; i--){
if (st >= 0 && s[st] >= g[i]) {
st--;
count++;
}
}
return count;
}
}

582

被折叠的 条评论
为什么被折叠?



