题目来源:
题目:
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
Example 1
Input: [3,0,1]
Output: 2
Example 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
解答:
感觉最大的问题就是怎么样去把题目搞清楚。
一个数组是从0到n的,里面的数也会是0到n,返回丢失的那个数。
这意味着,这个数组的长度现在实际长度为n=nums.length。
真实的原数组应该是n+1个数,最大值是n。
class Solution {
public int missingNumber(int[] nums) {
int sum=0;
for(int i=0;i<nums.length;i++){
sum +=nums[i]; //将现有所有数相加
}
return nums.length*(nums.length+1)/2-sum;
}
}
位操作:a^b^b =a
class Solution {
public int missingNumber(int[] nums) {
int xor = 0, i = 0;
for(i = 0;i<nums.length;i++){
xor ^=i ^ nums[i]; //异或
}
return xor ^ i; 这个i是 nums.length.即是最大值n。
}
}