Missing Number
[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?
[Solution2] sum: Time~O(n) Space~O(1) //overflow risk
missing = expected_sum - actual_sum = (0+n)(n+1)/2 - sum
class Solution { public: int missingNumber(vector<int>& nums) { //sol1: actual_sum = 0+...+n = (0+n)*(n+1)/2 //missing = actual_sum - sum int n = nums.size(), sum = 0; for(auto num : nums) sum += num; return 0.5*n*(n+1) - sum; } };
[Solution1] xor: Time~O(n) Space~O(1) //no overflow risk
xor all [i] and 0 to n: i^i=0, 0^missing=missing => final result = missing
[Tip]
- do not use for(auto...) since need to use counter "i"
- 0~n: n+1 numbers, nums[0~n-1]: n items => "for(i=0~n-1) res^=i^nums[i]" will not xor "n" => must init res=n
class Solution { public: int missingNumber(vector<int>& nums) { //sol2: xor all items and 0~n => (i^i)=0 so 0^missing=missing int n = nums.size(), res = n; for(int i=0; i<n; ++i) res ^= i ^ nums[i]; return res; } };
时间: 2024-10-31 18:06:44