LeetCode刷题【Array】 Missing Number

本文介绍了一种线性时间和常数空间复杂度的算法,用于找出包含0到n唯一整数的数组中缺失的一个数字。提供了三种解决方案,包括求和比较、累加下标以及XOR运算。

摘要生成于 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.

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?

解决方法一Runtime: 1 ms

public class Solution {
    public int missingNumber(int[] nums) {
        if(null==nums) return -1;
        int n=nums.length;
        int a=0;
        int b=0;
        boolean flag=false;
        a=(0+n)*(n+1)/2;
        for(int i=0;i<n;i++){
            b+=nums[i];
            if(nums[i]==0) flag=true;
        }
        if(flag==false) return 0;
        else return a-b;
    }
}

解决方法二Runtime: 1 ms 和方法一的思路基本一致,在循环遍历数组时,利用下标求和并减去数组值和便可得到缺失的数;

public class Solution {
    public int missingNumber(int[] nums) {
        if(null==nums) return -1;
        int sum=nums.length;
        for(int i=0;i<nums.length;i++){
            sum+=i-nums[i];
        }
        return sum;
    }
}
解决方法三: 利用XOR运算的性质,a^a^b=b;则对数组中的元素与下标XOR运算,最后余下的为缺失的数  Runtime:  2 ms

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

参考:

【1】https://leetcode.com/




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值