[LeetCode] [C] 41. First Missing Positive

7 篇文章 0 订阅
4 篇文章 0 订阅

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值