[LeetCode] [C] 41. First Missing Positive
来源:互联网 发布:dns域名解析软件 编辑:程序博客网 时间:2024/06/08 10:24
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;}
- [LeetCode] [C] 41. First Missing Positive
- [LeetCode]41.First Missing Positive
- LeetCode --- 41. First Missing Positive
- LeetCode 41.First Missing Positive
- [Leetcode] 41. First Missing Positive
- [leetcode] 41.First Missing Positive
- leetCode 41. First Missing Positive
- LeetCode 41. First Missing Positive
- leetcode 41. First Missing Positive
- Leetcode 41. First Missing Positive
- LeetCode 41. First Missing Positive
- [leetcode]41. First Missing Positive
- LeetCode-41.First Missing Positive
- leetcode 41. First Missing Positive
- [LeetCode] 41. First Missing Positive
- [LeetCode]--41. First Missing Positive
- leetcode 41. First Missing Positive
- leetcode 41.First Missing Positive
- thinkphp控制器数据赋值给模板js
- c语言:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数
- ECOMP已经开源成功,这次AT&T准备推动白盒路由操作系统DNOS
- SQL语法及重要的命令
- 四元数完全解析及资料汇总
- [LeetCode] [C] 41. First Missing Positive
- 考试时遇到的小问题
- Visio_2013安装破解
- 利用PIL生成图片验证码
- 1701H2 11.21 王建瑜 连续第二天
- C语言操作符
- Principle for Mac 3.6 简体中文完美汉化包 原型设计工具
- 2017山东医师定考题库(已去重)
- C++数字,数组,字符串