Problem:
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Idea:
sum / xor
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua class Solution { public: // Solution 1: Sum int missingNumber(vector<int>& nums) { int n = nums.size(); int x = (0+n)*(n+1)/2 - accumulate(nums.begin(), nums.end(), 0); return x; } // Solution 2: XOR int missingNumber(vector<int>& nums) { int n = nums.size(); int x = 0; for(int i=1;i<=n;++i) x = x ^ i ^ nums[i-1]; return x; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment