268. Missing Number

题目:

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

链接: http://leetcode.com/problems/missing-number/

题解:

求missing number。首先的想法是先求数列和,再减去数组里的数。这样的话要小心写法,有可能会overflow。我的写法就是会溢出的那种。

Time Complexity - O(n), Space Complexity - O(1)

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

 

也可以用Bit Manipulation,主要就是利用 0 ^ a = a, 以及 a ^ b ^ a = b

Time Complexity - O(n), Space Complexity - O(1)

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

 

二刷:

方法跟一刷一样。 我们首先从把所有0 ~ n的数异或一遍,接着再用这个数把数组中的数异或一遍,这样出现过两次的数都被置零, 剩下的就是 0 ^ missing num = mission num。

 

Java:

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

 

三刷:

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

 

假如输入时排序好的,那么则可以利用index和nums[index]的奇偶性来进行Binary Search

 

 

 

Reference:

https://leetcode.com/discuss/53802/c-solution-using-bit-manipulation

https://leetcode.com/discuss/56174/3-different-ideas-xor-sum-binary-search-java-code

https://leetcode.com/discuss/53937/simple-c-codes

https://leetcode.com/discuss/53790/1-lines-ruby-python-java-c

https://leetcode.com/discuss/53871/java-simplest-solution-o-1-space-o-n-time

https://leetcode.com/discuss/58647/line-simple-java-bit-manipulate-solution-with-explaination

posted @ 2015-12-06 03:25  YRB  阅读(1311)  评论(0编辑  收藏  举报