Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missi

来源:互联网 发布:java agent 做监控 编辑:程序博客网 时间:2024/05/17 22:32
<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 stubSystem.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;    }}



0 0