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.

Example 1

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

Example 2

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.

题意:

找一列连续数中消失的那个数。

思路:

1、再开一个bool数组,把原来出现的都设置成true,只需遍历一次找false的就行。

2、惊为天人的做法。求和之后,再用0-n之和减去出现的数之和。

代码:

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



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

猜你喜欢

转载自blog.csdn.net/qq_36718317/article/details/80204307
今日推荐