[LeetCode]268. Missing Number

本文介绍了一种寻找数组中缺失数字的算法,通过排序和遍历或利用高斯求和公式来实现线性时间和常数空间复杂度的要求。推荐使用第二种方法,即通过计算1到n的总和减去数组中所有数字的和来找到缺失的数字。

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值