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 class Solution {
2 public:
3     int missingNumber(vector<int>& nums) {
4         
5         int n = nums.size();
6         
7         return (0 + n)*(n + 1) / 2 - accumulate(nums.begin(), nums.end(), 0);
8     }
9 };

还有一种就是用异或XOR的性质了,X^X=0, X^0=X,满足交换律:

 1 class Solution {
 2 public:
 3     int missingNumber(vector<int>& nums) {
 4 
 5         int n = nums.size();
 6         int res = n;
 7         for (int i = 0; i < n; ++i)
 8         {
 9             res ^= nums[i] ^ i;
10         }
11         return res;
12     }
13 };

 

posted @ 2018-03-20 20:05  还是说得清点吧  阅读(764)  评论(0)    收藏  举报