<pre name="code" class="java">/*
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.
</pre><pre name="code" class="java">利用等差数列求和公式即可,空间复杂度为1,算法复杂度为O(n)
*/
</pre><pre name="code" class="java">public class FindLost {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new FindLost().missingNumber(new int[]{0,1,2,3,4,5,6}));
}
public int missingNumber(int[] nums) {
int length=nums.length;
int sum=0;
for(int i=0;i<length;i++)
{
sum+=nums[i];
}
return (length*length+length-2*sum)/2;
}
}
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missi
最新推荐文章于 2021-12-16 13:17:00 发布