LeetCode 268. Missing Number Posted on 2021-02-14 Edited on 2024-11-24 In LeetCode Bit ManipulationMathSwaption123456789class Solution {public: int missingNumber(vector<int>& nums) { int ans = nums.size(), i = 0; for (const int num : nums) ans ^= i++ ^ num; return ans; }};12345678class Solution {public: int missingNumber(vector<int>& nums) { int expectedSum = nums.size() * (nums.size() + 1) / 2; int actualSum = accumulate(nums.begin(), nums.end(), 0); return expectedSum - actualSum; }};1234567891011121314class Solution {public: int missingNumber(vector<int>& nums) { // reference: https://leetcode.com/problems/couples-holding-hands/discuss/113362/JavaC%2B%2B-O(N)-solution-using-cyclic-swapping const int n = nums.size(); for (int i = 0; i < n; ++i) for (int j = nums[i]; i != j && j != n; j = nums[i]) swap(nums[i], nums[j]); for (int i = 0; i < n; ++i) if (nums[i] != i) return i; return n; }};