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?
讀題
題目的意思就是給你n個數(shù),從0-n,找到缺失的那個數(shù)
思路
一種是常規(guī)的思路橱野,用0-n之和減去數(shù)組每個元素之和就是缺失的那個數(shù)
XOR的方式
The basic idea is to use XOR operation. We all know that abb =a, which means two xor operations with the same number will eliminate the number and reveal the original number.
In this solution, I apply XOR operation to both the index and value of the array. In a complete array with no missing numbers, the index and value should be perfectly corresponding( nums[index] = index), so in a missing array, what left finally is the missing number.
利用的公式就是a^b^b =a
,如果一個數(shù)組里面沒有元素是缺失的传睹,那么元素的下標和元素是對應(yīng)的
題解
public class Solution {
public static int missingNumber(int[] nums) {
int sum = nums.length*(nums.length+1)/2;
int m = 0;
for(int i:nums) m+=i;
return sum-m;
}
}
或者
public int missingNumber(int[] nums) {
int xor = 0, i = 0;
for (i = 0; i < nums.length; i++) {
xor = xor ^ i ^ nums[i];
}
return xor ^ i;
}