题目:
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?
思路:
将0~n和数组中的数字都进行异或,得到的结果即缺失的数字
具体代码如下:
public class Solution {
public int missingNumber(int[] nums) {
int result = 0;
int n = nums.length;
int j = 0;
for(int i: nums){
result = result^i^j;
j++;
}
return result^n;
}
}
本文介绍了一种线性时间复杂度和常数额外空间复杂度的方法来找出包含0到n范围内n个不同数字的数组中缺失的一个数字。通过使用异或运算,可以有效地找到缺失的数字。

1250

被折叠的 条评论
为什么被折叠?



