原题网址:https://leetcode.com/problems/missing-number/
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数字没有缺失的话,对0~n进行异或,可以得到一个确定的数字,然后对缺失数字的数组进行异或,可以得到另一个数字,这两个数字的异或,就是缺失的数字。
方法:通过异或运算找出缺失的数字。
public class Solution {
public int missingNumber(int[] nums) {
int missing = nums.length;
for(int i=0; i<nums.length; i++) {
missing ^= nums[i] ^ i;
}
return missing;
}
}