【Leetcode】:268. Missing Number 问题 in JAVA

本文介绍了一种寻找数组中缺失数字的方法,该数组包含从0到n的n个不同数字,但其中一个数字丢失了。通过排序数组并逐个检查元素来确定缺失的数字。此算法在时间复杂度为线性的情况下实现,但实际运行效率可能接近n log 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.

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?

----------------------------------------------------------------------------------------------------------------------------------------------------------------

首先分析题目,要求线性的时间复杂度,并且占用常数的空间,并没有说明测试用例是否排好序,如果先对测试用例排序时间复杂度就是nlgn了

先这样试试吧,看能不能通过。

下面的代码居然通过了,看来leetcode对nlgn和n的识别力不高?

public class Solution {
    public int missingNumber(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        Arrays.sort(nums);
        if (nums[0] != 0) {
            return 0;
        }
        if (nums[nums.length-1] != nums.length) {
            return nums.length;
        }
        int last = 0;
        for (int i = 1; i < nums.length; i++){
            if (nums[i] != last + 1) {
                return last + 1;
            }
            last = nums[i];
        }
        return last + 1;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值