[LeetCode268]Missing Number

来源:互联网 发布:linux查询逻辑cpu个数 编辑:程序博客网 时间:2024/05/21 20:39

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+1个整数,对题目给出的n个整数进行计数。最后扫描这个数组,就能找出缺失的那一个数。算法时间复杂度为O(n)。

class Solution {public:    int missingNumber(vector<int>& nums) {        int r,n=nums.size();        int che[n+1];        for(int i=0;i<n+1;i++)        {            che[i]=0;        }        for(int i=0;i<n;i++)        {            che[nums[i]]++;        }        for(int i=0;i<n+1;i++)        {            if(che[i]==0)            {                r=i;                break;            }        }        return r;    }};



0 0
原创粉丝点击