Leetcode: 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?
Best Solution: Bit manipulation
The basic idea is to use XOR operation. We all know that a^b^b =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.
1 class Solution { 2 public int missingNumber(int[] nums) { //xor 3 int res = nums.length; 4 for(int i=0; i<nums.length; i++){ 5 res ^= i; 6 res ^= nums[i]; 7 } 8 return res; 9 } 10 }
Summation approach:
1 public int missingNumber(int[] nums) { //sum 2 int len = nums.length; 3 int sum = (0+len)*(len+1)/2; 4 for(int i=0; i<len; i++) 5 sum-=nums[i]; 6 return sum; 7 }
因为输入数组是0,1,2,...,n。 把nums[i]放到i的位置上. nums[i] != i的即为missing number.
注意6-9行不可先令 temp = nums[i]
1 public class Solution { 2 public int missingNumber(int[] nums) { 3 int res = nums.length; 4 for (int i=0; i<nums.length; i++) { 5 if (nums[i] < nums.length && nums[nums[i]] != nums[i]) { 6 int temp = nums[nums[i]]; 7 nums[nums[i]] = nums[i]; 8 nums[i] = temp; 9 i--; 10 } 11 } 12 for (int i=0; i<nums.length; i++) { 13 if (nums[i] != i) res = i; 14 } 15 return res; 16 } 17 }