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;
    }
}

 

posted on 2019-05-12 02:19  一直走在路上  阅读(93)  评论(0编辑  收藏  举报

导航