码迷,mamicode.com
首页 > 其他好文 > 详细

Missing Number LT268

时间:2019-05-12 10:37:51      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:one   put   lex   opera   distinct   ide   solution   div   algorithm   

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

标签:one   put   lex   opera   distinct   ide   solution   div   algorithm   

原文地址:https://www.cnblogs.com/taste-it-own-it-love-it/p/10850962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!