LeetCode 268 Missing Number (Missing Number)
Translation
Given a number that contains different numbers from 0, 1, 2..., n, find a lost number from the array. For example, given nums = [0, 1, 3], 2 is returned. Note: Your algorithm should run in linear time complexity. Can you implement it with only the complexity of the constant space?
Original
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?
Analysis
Because the array can be very large and its size is not fixed, the hash table should be useless.
The middle part of the thinking process is omitted, and the following question is done first. When I return to this question, I suddenly have a thought.
LeetCode 319 Bulb Switcher (Bulb switching) (algorithm found from law ......)
For example, in the array from zero to 32146, the loss number is 4687.
We can calculate the sum of all numbers from 0 to 32146:
expectedSum:516666585
We can also calculate the sum of all the numbers from 0 to 32146 and lose 4687:
actualSum:516661898
Yes, that's right ......
The Code is as follows:
Code
<code class=" hljs cpp">int missingNumber(vector<int>& nums) { int expectedSum = 0, actualSum = 0; for (int i = 1; i <= nums.size(); ++i) { expectedSum += i; } for (int i = 0; i < nums.size(); ++i) { actualSum += nums[i]; } return expectedSum - actualSum;}</int></code>