数组nums
包含从0
到n
的所有整数,但其中缺了一个。请编写代码找出那个缺失的整数。你有办法在O(n)时间内完成吗?
注意:本题相对书上原题稍作改动
示例 1:
输入:[3,0,1]
输出:2
示例 2:
输入:[9,6,4,2,3,5,7,0,1]
输出:8
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int missingNumber(int[] nums) {
if (nums == null) {
return -1;
}
boolean[] checked = new boolean[nums.length + 1];
for (int num : nums) {
checked[num] = true;
}
for (int i = 0; i < checked.length; i++) {
if (!checked[i]) {
return i;
}
}
return -1;
}
}
//leetcode submit region end(Prohibit modification and deletion)