268 Missing Number

本文介绍了三种高效算法来解决寻找1到n中缺失数字的问题:公式计算法、异或位运算法及二分查找法。文章提供了具体的实现代码,并讨论了不同算法的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

本题的意思是,从1到n的整数,其中某个数丢失了,替代它的是0。要我们找出这 个丢失的数。
方法1,我们可以用公式计算出从1到n的和,减去实际数组的总和,差值就是那个 丢失的数。
方法2,利用异或位运算,把数组中的每一个数,与1到n进行按位异或,最后剩下 的,就是丢失的数。
方法3,二分查找。首先把数组排序,设中间元素为 nums[mid] ,如果 nums[mid] 的值大于其下标,说明丢失的数字在左边,反之则在右边。时间复杂度 O(nlogn) ,比前面两个方法慢,但是如果题目给的数组是事先排好序的,那么复杂度就是 O(log n) ,所以这个方法还是很有意义的。
class Solution {
    public int missingNumber(int[] nums) {
        int n = nums.length;
        int sum = (n + 1) * n / 2;
        for (int x : nums) {
            sum -= x;
        }
        return sum;
    }
}

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

public class Solution {
    public static int missingNumber(int[] nums) {
        Arrays.sort(nums);
        int begin = 0;
        int end = nums.length;
        while (begin != end) {
            int mid = begin + (end - begin) / 2;
            if (mid < nums[mid]) {
                end = mid;
            } else {
                begin = mid + 1;
            }
        }
        return end;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值