leetcode——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项和公式来解决,补齐缺项,所以要按n+1项来计算,故完整n+1项和为n(n+1),减去数组中的n项和即可得到缺失项的值,算法简单易实现。

class Solution {
public:
	int missingNumber(vector& nums) {
		int sum=0, n=nums.size();
		for(int i=0; i




你可能感兴趣的:(leetcode——Missing Number)