题目:
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?
题意:
就是给定一个n的数组,然后计算出这个数组中缺失的那个数字。但是要求时间复杂度为O(n),以及不能生成额外的空间复杂度。所以此题在进行求解的时候,LZ一开始想到的方法是采用排序,注意了,各种排序算法的时间复杂度最好的情况也为O(nlogn),所以根本不可能在O(n)之内的,所以我们不可能采用这种方法来求解,于是看题意,发现有distinct number,也就是说,是n个连续的数字,那么可以分别计算连续的数字的和和现在已有的数组中的数字的和,然后将这两个和相减,得到的就是这个确实的值。这种方法非常巧妙,是利用了本题中的因为这n个数字是从0开始的,而且是连续的,所以可以采用这种方法来做,就比较巧妙。这也是根据本题的题意而来做的。
public class Solution
{
public static int missingNumber(int[] nums)
{
int length = nums.length;
//System.out.println(length);
int sum1 = 0;
int sum2 = 0;
for(int i = 1; i <= length; i++)
sum1 += i;
for(int j = 0; j < length; j++)
sum2 += nums[j];
return sum1 - sum2; //注意这里的0不考虑,所以可以省去这个0的情况。
}
}