Missing Number
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:
linear runtime complexity
给定一数组,包含\(n\)个不同的数,数从集合\(\{ 0,1,2...,n\}\)取出,
找出数组中缺失的哪个数。
即,从\(\{ 0,1,2...,n\}\) \(n+1\)个数中取走一个数\(x\),剩下\(n\)个数的数组,根据这个数组找出这个缺失的数,
public class Solution {
public int missingNumber(int[] nums) {
if (nums.length<1){
return 0;
}
int res=0;
for (int i = 0; i < nums.length; i++) {
res=i;
if (i!=nums[i]){
return res;
}
}
return res+1;
}
}
失误了,没有考虑到题目并没有告诉我们数组是否是排序好了的。
而上面的代码是在数组是有序的这个条件下。
修改:
对于完整的数组\(array=\{0...n\}\),数组之和\(Sum\)为\(N*(N+1)/2\),\(N=array.length-1\)
则缺失的数字就为 \(Sum-(sum(nums))\)
public int missingNumber(int[] nums){
int sum=0;
for (int i = 0; i < nums.length; i++) {
sum+=nums[i];
}
return nums.length*(nums.length+1)/2-sum;
}