268. Missing Number

本文介绍了一种高效的算法来解决寻找从0到n中缺失的一个整数的问题。通过使用数学公式、位操作或者数组交换等方法,该算法能在线性时间内找到缺失的数字,并且只使用常数级别的额外空间。

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

iven 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?


由于题干说明去取的数是从0一直到n,所以例如13,14,15……20这样的序列是不会出现的。

先把两个边界处理一下,缺0的情况和完整的情况,缺0的话就是n项和了,完整的话就是n-1项和。

再处理一般情况,一般情况直接用min加到max应该的和减去前面的sum就是所求。

public int missingNumber(int[] nums)
	{
		int len=nums.length;
		if(len<1)
			return 0;
		
		long min=Integer.MAX_VALUE;
		long max=Integer.MIN_VALUE;
		long sum=0;
		
		for(int i=0;i<len;i++)
		{
			min=Math.min(nums[i], min);
			max=Math.max(nums[i],max);
			sum+=nums[i];
		}
		
		if(sum==(len*(len+1)/2))
			return 0;
		
		if(sum==(len*(len-1)/2))
			return (int) (max+1);
		
	    return  (int) ((min+max)*(len+1)/2-sum);
	}



简洁版

https://discuss.leetcode.com/topic/24535/4-line-simple-java-bit-manipulate-solution-with-explaination/3

since the n numbers are from [0, n], we can just add all the numbers from [0, n] together and minus the sum of the n-1 numbers in array.

public static int missingNumber(int[] nums) {
    int sum = nums.length;
    for (int i = 0; i < nums.length; i++)
        sum += i - nums[i];
    return sum;
}


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

位操作版

The basic idea is to use XOR operation. We all know that a^b^b =a, which means two xor operations with the same number will eliminate the number and reveal the original number.
In this solution, I apply XOR operation to both the index and value of the array. In a complete array with no missing numbers, the index and value should be perfectly corresponding( nums[index] = index), so in a missing array, what left finally is the missing number.

public int missingNumber(int[] nums) {

    int xor = 0, i = 0;
	for (i = 0; i < nums.length; i++) {
		xor = xor ^ i ^ nums[i];
	}

	return xor ^ i;
}

---------------------------------------------------------
交换元素,把相应的数放在相应的index上,使得num[i]=i+1,然后从头到尾第一个不满足这个关系的数就是缺失的数,全部都满足的话,缺失的是0.
public class Solution {
    public static int missingNumber(int[] nums)
	{
		int len=nums.length;
		if(len==0)
			return 0;
		
		for(int i=0;i<len;i++)
		{
			while(nums[i]!=0&&nums[i]!=i+1)
			{
				int temp=nums[nums[i]-1];
				nums[nums[i]-1]=nums[i];
				nums[i]=temp;
			}
		}
		
		int missing=-1;
		for(int i=0;i<len;i++)
			if(nums[i]!=i+1)
			{
				missing=i;
				break;
			}
		
		return missing+1;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值