Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
这个题目很简单,应该拿到题目就会的,但是有最优解;我先给出了这移动比较直白的思路:
方法1:
public int missingNumber(int[] nums) {
int length = nums.length;
Set<Integer> set = new HashSet<>();
for (int i = 0; i < length + 1; i++) {
set.add(i);
}
for (int i = 0; i < length; i++) {
if (set.contains(nums[i])) {
set.remove(nums[i]);
}
}
return (int) set.toArray()[0];
}
这种思路最容易想到,但是效率不高;
时间复杂度:O(n);
空间复杂度:O(n);
方法2:
利用加减的方法,自己没有考虑到边界问题,可以注意下边界问题,但是为了问题解决的方便,我先没考虑它的值超过Integer.Max_VALUE的解决办法。直接计算:
public int missingNumber2(int[] nums) {
int sum = 0;
int n = nums.length;
int totalSum = (n + 1) * n / 2;
for (int i = 0; i < n; i++) {
sum += nums[i];
}
return totalSum-sum;
}
时间复杂度:O(n)
空间复杂度:O(1)