Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.spa
Example 1:code
Input: [3,0,1] Output: 2
Example 2:blog
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?ci
1 class Solution { 2 public int missingNumber(int[] nums) { 3 int result = nums.length; 4 for(int i = 0; i < nums.length; ++i) { 5 result ^= (nums[i] ^ i); 6 } 7 return result; 8 } 9 }
Idea 2. Math, the sum of sequencial numbers, sum[0...N] = (1+N)*N/2;rem
1 class Solution { 2 public int missingNumber(int[] nums) { 3 int N = nums.length; 4 int result = (1+N) * N/2; 5 for(int i = 0; i < nums.length; ++i) { 6 result -= nums[i]; 7 } 8 return result; 9 } 10 }
Idea 3. Sortit
Time complexity: O(NlgN)io
Space complexity: O(1)class
class Solution { public int missingNumber(int[] nums) { int N = nums.length; Arrays.sort(nums); if(nums[0] != 0) { return 0; } if(nums[N-1] != N) { return N; } for(int i = 1; i < nums.length; ++i) { if(nums[i] != i) { return i; } } return -1; } }