268. Missing Number(Java)

本文介绍了几种寻找数组中缺失数字的高效算法,包括使用数学公式、位运算以及二分搜索等方法,并对每种方法的时间复杂度进行了分析。

注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注

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:

class Solution {
    public int missingNumber(int[] nums) {
        int len = nums.length;
        int sum = (1 + len) * len / 2;
        for (int n : nums) 
            sum -= n;
        return sum;
    }
}
// 相比于上面的方法可以防止溢出
class Solution {
    public int missingNumber(int[] nums) {
        int sum = nums.length;
        for (int i = 0; i < nums.length; i ++) 
            sum += i - nums[i];  
        return sum;
    }
}

代码2:利用A ^ A = 0,A ^ A ^ B = B,且满足结合律和交换律

class Solution {
    public int missingNumber(int[] nums) {
        int res = nums.length;
        for (int i = 0; i < nums.length; i ++) {
            res ^=  i ^ nums[i];
        }
        return res;
    }
}

代码3:若数组有序,可以考虑用二分搜索

class Solution {
    public int missingNumber(int[] nums) {
        Arrays.sort(nums);
        int left = 0, right = nums.length, mid = (left + right) / 2;
        
        while (left < right) {
            // mid为本来应该的平均数
            mid = (left + right) / 2;
            // 若实际偏大,则抽走了小的数,则抽走的数在左边
            if (nums[mid] > mid) 
                right = mid;
            // 若实际偏小,则抽走了大的数,则抽走的数在右边
            else left = mid + 1;
        }
        return left;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值