In this program,
I used Bubble Sort to sort the array first.
Then, I declared a variable "count" to represent the First Missing Positive Integer.
(Because the way I used it is similar to when I am counting something.)
Simply speaking,
I start counting when nums[i] > 0.
(We are finding the first missing positive integer, so the numbers smaller than 0 make no sense.)
After submitting once,
I found that there could be duplicate numbers.
So if (nums[i]==nums[i-1]) count--;
You'll notice that the value difference between nums[i] and nums[i+1] is always 0 or 1,
if it's not,
there must be a missing positive integer.
As count++ and count-- goes,
when nums[i]!=count,
the result comes out.
For example,
nums: [-1, 0, 1, 2, 2, 4]
First missing positive integer: 3
when nums[i]>0, counting starts, and "i" is still increasing.
i=2: nums[i]=1, count=1; i++,count++;
i=3: nums[i]=2, count=2; i++,count++;
i=4: nums[i]=2, count=2; i++,count++,count--; (at this moment, nums[i]==nums[i-1], so count--)
i=5: nums[i]=4, count=3;
Here, nums[i]!=count, the answer comes.
The Runtime of the program is 3 ms.
The length of the code is 465 Bytes.
int firstMissingPositive(int* nums, int numsSize) {
int i,j,tmp,count=1;
for (i=0; i<numsSize; i++) {
for (j=i+1; j<numsSize; j++) {
if (nums[i]>nums[j]) {
tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
}
}
for (i=0; i<numsSize; i++) {
if (nums[i]>0) {
if (i>0)
if (nums[i]==nums[i-1]) count--;
if (nums[i]==count) count++;
else return count;
}
}
return count;
}