fork download
  1. #include <bits/stdc++.h>
  2. int firstMissing(int arr[], int n)
  3. {
  4. for(int i=0;i<n;i++){
  5. while (arr[i] > 0 && arr[i]<=n && arr[arr[i] - 1] != arr[i]) {
  6. int temp = arr[i];
  7. arr[i] = arr[temp - 1];
  8. arr[temp - 1] = temp;
  9. }
  10. }
  11.  
  12. for (int i=0; i<n; ++i) {
  13. if (arr[i]!=i+1) {
  14. return i+1;
  15. }
  16. }
  17.  
  18. return n+1;
  19. }
  20. int main() {
  21. int arr[] = {3, 2, -6, 1, 0};
  22. int n = sizeof(arr) / sizeof(arr[0]);
  23. std::cout << "The first missing positive integer is: " << firstMissing(arr, n) << std::endl;
  24. return 0;
  25. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
The first missing positive integer is: 4