[Lintcode] Find the Missing number looking for lost numbers

Source: Internet
Author: User
Tags lintcode

Given An array contains N numbers of 0. N, find which number doesn ' t exist in the array.

Example

Given N = 3 [0, 1, 3] and the array, return 2 .

Challenge

Do it in-place with O (1) extra memory and O (n) time.

This question is the original question on Leetcode, please see my previous blog missing number missing. The problem with two ways to solve problems, but lintcode OJ more stringent, there is a large data set, summation will exceed the range of int, so for the solution of a word need to use long to calculate the sum of the array, the rest of the same, remember to turn the result into an int, see the code is as follows:

Solution One:

classSolution { Public:    /** * @param nums:a vector of integers * @return: an integer*/    intFindmissing (vector<int> &nums) {        //Write your code here        Longsum =0, n =nums.size ();  for(Auto &a:nums) {Sum+=A; }        return(int) (n * (n +1) *0.5-sum); }};

There is no difference between bit manipulation and previous bits, see the code below:

Solution Two:

classSolution { Public:    /** * @param nums:a vector of integers * @return: an integer*/    intFindmissing (vector<int> &nums) {        //Write your code here        intres =0;        Sort (Nums.begin (), Nums.end ());  for(inti =0; I < nums.size (); ++i) {res^= Nums[i] ^ (i +1); }        returnRes; }};

[Lintcode] Find the Missing number looking for lost numbers

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.