要求返回数组,但不确定是否能够把数组完全填充
若题目要求的返回类型是数组类型,但不确定是否能够把数组完全填充。这种情况以往使用链表保存计算结果,待计算结束再去把链表转成数组,这样太麻烦了,可以直接使用数组,利用位移变量判断最终的数组内容是否完全被填充,例如,210. 课程表 II中的这段代码:
int[] ans = new int[numCourses];
int index = 0;
while(!que.isEmpty()){
int tmp = que.poll();
ans[index++] = tmp;
HashSet<Integer> adj = adjoin[tmp];
for(Integer ad : adj){
if(--incnt[ad] == 0){
que.offer(ad);
}
}
}
return index == numCourses ? ans : new int[0];
通过index确定数组ans是否填满了数值。