Missing Number LT268
Posted taste-it-own-it-love-it
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Missing Number LT268相关的知识,希望对你有一定的参考价值。
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
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Idea 1. Bitwise operation, Xor, 0^x = x, 0^0 = 0, 0^1 = 1, Xor [0-N], the remaining number is the result.
Time complexity: O(N)
Space complexity: O(1)
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;
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. Sort
Time complexity: O(NlgN)
Space complexity: O(1)
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; } }
以上是关于Missing Number LT268的主要内容,如果未能解决你的问题,请参考以下文章