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?
两种方法:
(1)先将数组排序,排成0到n的形式,很有可能题目一开始就是排好的,面试的时候可以问一下。然后for循环逐一比较,找出缺省的那个数;
(2) 高斯求和求出1到n(数组长度!!!这一步非常关键 n=nums.length)所有数的和,再用这个和减去数组中的所有元素,这个方法十分方便。推荐使用。
class Solution {
public int missingNumber(int[] nums)
{
// 方法1
int n = nums.length, i = 0;
//以下是排序,方法可以随意选择
Arrays.sort(nums);
// while (i<n)
// {
// while (nums[i]!=i && nums[i]<n) {
// int t = nums[i];
// nums[i] = nums[t];
// nums[t] = t;
// }
// ++i;
// }
for (i=0; i<n; ++i)
if (nums[i]!=i) return i;
return n;
// 方法2
long N=nums.length;
long sum=N*(N+1)/2;
for(int i : nums){
sum -= i;
}
return (int) sum;
}
}
本文介绍了一种寻找数组中缺失数字的算法,通过排序和遍历或利用高斯求和公式来实现线性时间和常数空间复杂度的要求。推荐使用第二种方法,即通过计算1到n的总和减去数组中所有数字的和来找到缺失的数字。
366

被折叠的 条评论
为什么被折叠?



