There are three methods to solve this problem: bit manipulation, rearrangement of the array, and math tricks.
Bit Manipulation
1 class Solution {2 public:3 int missingNumber(vector & nums) {4 int ans = nums.size(), i = 0;5 for (int num : nums)6 ans ^= (num ^ (i++));7 return ans;8 }9 };
Rearrangement
1 class Solution { 2 public: 3 int missingNumber(vector & nums) { 4 int n = nums.size(), r = n; 5 for (int i = 0; i < n; i++) { 6 while (nums[i] != i) { 7 if (nums[i] == n) { 8 r = i; 9 break;10 }11 swap(nums[i], nums[nums[i]]);12 }13 }14 return r;15 }16 };
Math
1 class Solution {2 public:3 int missingNumber(vector & nums) {4 int n = nums.size(), ans = n * (n + 1) / 2;5 for (int num : nums) ans -= num;6 return ans;7 }8 };