[LeetCode]268. Missing Number

来源:互联网 发布:Js undefunde 与 null 编辑:程序博客网 时间:2024/05/19 10:56

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;    }}
原创粉丝点击