forked from shivammaniharsahu/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirst Missing positive.cpp.txt
More file actions
73 lines (63 loc) · 1.98 KB
/
First Missing positive.cpp.txt
File metadata and controls
73 lines (63 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <bits/stdc++.h>
using namespace std;
/* Utility to swap to integers */
void swap(int* a, int* b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
/* Utility function that puts all
non-positive (0 and negative) numbers on left
side of arr[] and return count of such numbers */
int segregate(int arr[], int size)
{
int j = 0, i;
for (i = 0; i < size; i++) {
if (arr[i] <= 0) {
swap(&arr[i], &arr[j]);
j++; // increment count of non-positive integers
}
}
return j;
}
/* Find the smallest positive missing number
in an array that contains all positive integers */
int findMissingPositive(int arr[], int size)
{
int i;
// Mark arr[i] as visited by making arr[arr[i] - 1] negative.
// Note that 1 is subtracted because index start
// from 0 and positive numbers start from 1
for (i = 0; i < size; i++) {
if (abs(arr[i]) - 1 < size && arr[abs(arr[i]) - 1] > 0)
arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
}
// Return the first index value at which is positive
for (i = 0; i < size; i++)
if (arr[i] > 0)
// 1 is added because indexes start from 0
return i + 1;
return size + 1;
}
/* Find the smallest positive missing
number in an array that contains
both positive and negative integers */
int findMissing(int arr[], int size)
{
// First separate positive and negative numbers
int shift = segregate(arr, size);
// Shift the array and call findMissingPositive for
// positive part
return findMissingPositive(arr + shift, size - shift);
}
// Driver code
int main()
{
int arr[] = { 0, 10, 2, -10, -20 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
int missing = findMissing(arr, arr_size);
cout << "The smallest positive missing number is " << missing;
return 0;
}