[LeetCode] 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.html

Example 1java

Input: [3,0,1]
Output: 2

Example 2python

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?面試

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.數組

給n個數,0到n之間有一個數字缺失了,讓找到這個缺失數字。要求線性時間複雜度和常數級的額外空間複雜度。this

解法1:排序,而後二分查找。此題數組不是排序的,因此適合。但面試時,若是問道要知道。spa

解法2:求差值,用0~n個數的和減去給定數組數字的和,差值就是要找的數字。code

解法3:位操做Bit Manipulation,將這個數組與0~n之間完整的數異或一下累加到res,相同的數字異或後都變爲了0,最後剩下的結果就是缺失的數字。htm

Java:blog

class Solution {
    public int missingNumber(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int result = 0;

        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (result != nums[i]) {
                return result;
            }
            result++;
        }
        return nums.length;
    }
}  

Java:

class Solution {
    public int missingNumber(int[] nums) {
        int xor = 0, i = 0;

        for (i = 0; i < nums.length; i++) {
            xor = xor ^ i ^ nums[i];
        }

        return xor ^ i;
    }
}  

Python:

def missingNumber(self, nums):
    n = len(nums)
    return n * (n+1) / 2 - sum(nums)  

Python:

class Solution(object):
    def missingNumber(self, nums):
        return sum(xrange(len(nums)+1)) - sum(nums)

Python:

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return reduce(operator.xor, nums, \
                      reduce(operator.xor, xrange(len(nums) + 1)))  

C++: 用等差數列公式

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int sum = 0, n = nums.size();
        for (auto &a : nums) {
            sum += a;
        }
        return 0.5 * n * (n + 1) - sum;
    }
};

C++:

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int res = 0;
        for (int i = 0; i < nums.size(); ++i) {
            res ^= (i + 1) ^ nums[i];
        }
        return res;
    }
};

 

相似題目:

[CareerCup] 5.7 Find Missing Integer 查找丟失的數

 

All LeetCode Questions List 題目彙總

相關文章
相關標籤/搜索