您的位置:首页 > 其它

Leetcode 268. Missing Number(Easy)

2018-02-06 21:01 357 查看

1.题目

Given an array containing n distinct numbers taken from 
0, 1, 2, ..., n
, find the one that is
missing from the array.

翻译:给定一个包含从0,1,2...,n中选取出的n个不同的数字,找到数组中被忽略的数字。

Example 1
Input: [3,0,1]
Output: 2


Example 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8


Note:

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

翻译:你的算法运行时间应该是线性的(O(n)),你能只用常数级别的额外空间吗?

2.思路

错误思路:之前想的是,先类似排序,但是排序方法就没有找到线性级别的;之后想到的是用hashmap,记录,但是空间不符合要求。思考无果,上网找答案。

正确思路:采用位的异或运算。首先,将0-n的所有数字进行异或运算得sum1;再将nums数组中的所有数字进行异或运算得到sum2.由a^a=0;可知,sum1与sum2异或后,将得到被遗漏的数字。

3.算法

public int missingNumber(int[] nums) {
int n=nums.length;

int sum=0;
for(int i=0;i<=n-1;i++){
sum=sum^i^nums[i];
}
int res=sum^n;
return res;

}

4.总结

 位运算的方法很实用,也很巧妙。曾经一次电话面试,考官出题:能否在不利用第三个数的情况下,将a和b的值进行交换。
这也是根据异或算法进行的。
a=a^b;
 b=b^a;
 a=a^b;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: