1: class Solution {
2: public:
3: int missingNumber(vector<int>& nums) {
4: int n = nums.size();
5: int res = 0;
6: for (int i = 0; i <= n; i++) {
7: res ^= i;
8: }
9: for (int i = 0; i < nums.size(); i++) {
10: res ^= nums[i];
11: }
12: return res;
13: }
14: };
Saturday, August 13, 2016
268. Missing Number
This idea comes from the problem of "136. Single Number", i.e. xor cancels the same number. So we can xor all the numbers from 0 to n first. And then xor the numbers in the input array. The remaining number must be the missing number.
Labels:
array,
bit manipulation,
leetcode,
microsoft
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment