6.6—排序—First Missing Positive

来源:互联网 发布:儿童初学画画软件 编辑:程序博客网 时间:2024/06/06 15:36
描述
Given an unsorted integer array, find the first missing positive integer.
For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.

#include<iostream>using namespace std;void swap(int &a, int &b){int temp = a;a = b;b = temp;}void BucketSort(int a[], int n){for (int i = 0; i < n;i++){while (a[i] != i + 1){if (a[i]<=0 || a[i]>n || a[i] == a[a[i] - 1])break;swap(a[i], a[a[i] - 1]);}}}int FirstMissingPositive(int a[], int n){BucketSort(a, n);for (int i = 0; i < n; i++)if (a[i] != i + 1)return i + 1;return n + 1;}int main(){const int n = 6;int a[n] = { 2, 0, 6, 3, 4, 1 };BucketSort(a, n);int first = FirstMissingPositive(a, n);cout << first << endl;}