268. Missing Number - Easy

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?

 

M1: 求和

因为是由0~n组成的数组,只缺少一个数字,可以先通过公式计算出应有的和,再遍历数组一个个减去,剩下的数就是missing number

时间:O(N),空间:O(1)

class Solution {
    public int missingNumber(int[] nums) {
        int n = nums.length;
        int sum = n * (n + 1) / 2;
        for(int i = 0; i < n; i++) {
            sum -= nums[i];
        }
        return sum;
    }
}

 

M2: hash table

hashset,扫描两次,第一次把nums中元素放进set,第二次遍历0~n,找出map中没有的元素

time: O(n), space: O(n)

class Solution {
    public int missingNumber(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int n : nums) {
            set.add(n);
        }
        
        int res = 0;
        for(int i = 0; i <= nums.length; i++) {
            if(!set.contains(i)) {
                res = i;
                break;
            }
        }
        return res;
    }
}

 

hashset, 扫描两次,第一次把1~n所有元素加入set,第二次把nums中的元素从set中删除,剩下的就是missing number

time: O(n), space: O(n)

class Solution {
    public int missingNumber(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int n : nums) {
            set.add(n);
        }
        for(int i = 1; i <= nums.length; i++) {
            if(!set.remove(i)) {
                return i;
            }
        }
        return 0;
    }
}

 

 

M3: bit operation

先把0~n全部xor,再对nums中的元素全部xor

time: O(n), space: O(1)

class Solution {
    public int missingNumber(int[] nums) {
        int res = 0;
        for(int i = 0; i <= nums.length; i++) {
            res ^= i;
        }
        for(int n : nums) {
            res ^= n;
        }
        return res;
    }
}

 

posted @ 2018-11-29 17:01  fatttcat  阅读(204)  评论(0编辑  收藏  举报