LeetCode 题解(194) : 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?

题解:

从0到n的数列的求和公式:(nums.length  + 0) * (nums.length + 1) / 2.

C++版:

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int sum = 0;
        for(int i = 0; i < nums.size(); i++)
            sum += nums[i];
        int temp = nums.size() * (nums.size() + 1) / 2;
        if(temp > sum)
            return temp - sum;
        return 0;
    }
};

Java版:

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

Python版:

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sum = 0
        for i in nums:
            sum += i
        temp = len(nums) * (len(nums) + 1) / 2
        if temp > sum:
            return temp - sum
        return 0


你可能感兴趣的:(LeetCode,Algorithm,面试题)