LeetCode 268 Missing Number (Missing Number)

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.