Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
,
find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
----------------------------------------------------------------------------------------------------------------------------------------------------------------
首先分析题目,要求线性的时间复杂度,并且占用常数的空间,并没有说明测试用例是否排好序,如果先对测试用例排序时间复杂度就是nlgn了
先这样试试吧,看能不能通过。
下面的代码居然通过了,看来leetcode对nlgn和n的识别力不高?
public class Solution {
public int missingNumber(int[] nums) {
if (nums.length == 0) {
return 0;
}
Arrays.sort(nums);
if (nums[0] != 0) {
return 0;
}
if (nums[nums.length-1] != nums.length) {
return nums.length;
}
int last = 0;
for (int i = 1; i < nums.length; i++){
if (nums[i] != last + 1) {
return last + 1;
}
last = nums[i];
}
return last + 1;
}
}