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