The first missing integer

Source: Internet
Author: User

Ask for the first missing integer problem:

Given an array of a[0...n-1], find the first positive integer that is not in the array, starting with 1.

For example: 3,5,1,2,-3,7,14,8; return: 4.

Problem Analysis:

You can put the number you find in the correct location, and if you finally find that an element has not been found, that element is what you are seeking.

Suppose the number of previous i-1 has been found and has been correctly stored in the front i-1 bit. Can be divided into the following situations:

    • A[i] = i, i++;
    • 1<a[i]<i, discard;
    • I<a[i]<n, when a[i] = A[a[i]], discard; When not equal, exchange;
    • A[i]>n, discard.

Program implementation:

1 /***************************************2 FileName FindFirstMissingNum.cpp3 Author:godfrey4 CREATEDTIME:2016/5/35 ****************************************/6#include <iostream>7#include <cstring>8#include <vector>9#include <algorithm>Ten#include <stdio.h> One#include <stdlib.h> A  - using namespacestd; -  the intFindfirstmissingnum (intAintsize) { -     inti =1; -A--; -      while(i<=size) { +         if(A[i] = =i) { -i++; +         } A         Else if((A[i] < i) | | (A[i] > size) | | (A[i] = =A[a[i])) { atA[i] =A[size]; -Size--; -         } -         Else{//if (A[i] > i) - swap (a[i],a[a[i]]); -         } in     } -     returni; to } + intMain () - { the     intA[] = {3,5,1,2,-3,7, -,8}; *     intFirstmissingnum = Findfirstmissingnum (A,sizeof(a)/sizeof(int)); $cout<<"The firstmissingnum:";Panax Notoginsengcout<<firstmissingnum<<Endl; -     return 0; the}

Operation Result:

Reprint please specify the source:

C + + Blog Park: godfrey_88

http://www.cnblogs.com/gaobaoru-articles/

The first missing integer

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.