leetcode268: Missing Number

该博客介绍了如何解决LeetCode上的第268题,即在一个包含n个不同整数的数组中找出缺失的那个数字。通过创建一个包含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.

For example,

Given nums = [0, 1, 3] return 2.

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

注意:将数组放在新数组中,再将数字1-n放入新数组中。将新数组中所有元素进行异或,结果就是那个没有重复的数字,也就是Missing Number

例如:

int[] array={0,1,2,4,5}
在新数组中先放入0-5,再放入array中所有元素

int[] newarray={0,1,2,3,4,5,0,1,2,4,5}
只有3没有重复两次。

进行异或后,返回单个元素3

	public int missingNumber(int[] nums) {
		int[] ar = new int[2 * nums.length + 1];
		for (int i = 0; i <= nums.length; i++)
			ar[i] = i;
		for (int i = 0; i < nums.length; i++)
			ar[i + nums.length + 1] = nums[i];
		int result = ar[0];
		for (int i = 1; i < ar.length; i++)
			result = result ^ ar[i];
		return result;
	}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值