[leetcode_268] Missing Number

给定数列中,从 0 到 n,但是缺少一个数字 i。求 i 为多少。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int sum = 0;
        int max = 0;
        bool isZero = false;
        for (int i = 0; i < nums.size(); i++) {
            sum += nums[i];
            if (nums[i] >= max) {
                max = nums[i];
            }
            if (nums[i] == 0) {
                isZero = true;
            }
        }
        int oSum = (0 + max) * (max - 0 + 1) / 2; 
        if (oSum == sum) {
            if (!isZero) {
                return 0;
            } else {
                return max + 1;
            }
        } else {
            return oSum - sum;
        }
    }
};
Licensed under CC BY-NC-SA 4.0