leetcode: First Missing Positive
来源:互联网 发布:iis中将端口改为81 编辑:程序博客网 时间:2024/04/30 07:14
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
http://tech-wonderland.net/blog/leetcode-first-missing-positive.html
就是把出现的正整数a都放在a-1的位置,然后从头开始历遍,发现A[i] != i + 1的情况就是所要的结果
class Solution {public: int firstMissingPositive(int A[], int n) { if( A == NULL || n == 0) return 1;//这里返回 for( int i = 0; i < n; ){ if( A[i] != i + 1 && A[i] > 0 && A[i] <= n && A[i] != A[A[i]-1])//这里A[i] > 0不能用A[i]代替 swap( A[i], A[A[i]-1]);//不改变i的值,一直交换,直到不满足上述条件之一 else ++i; } for( int j = 0; j < n; ++j) if( A[j] != j + 1) return j + 1; return n + 1; }};
0 0
- LeetCode: First Missing Positive
- LeetCode First Missing Positive
- LeetCode: First Missing Positive
- [Leetcode] First Missing Positive
- [LeetCode] First Missing Positive
- [Leetcode] First Missing Positive
- leetcode First Missing Positive
- LeetCode First Missing Positive
- [leetcode] first missing positive
- LeetCode: First Missing Positive
- [LeetCode]First Missing Positive
- LeetCode-First Missing Positive
- [leetcode] First Missing Positive
- [LeetCode] First Missing Positive
- LeetCode - First Missing Positive
- LeetCode | First Missing Positive
- Leetcode: First Missing Positive
- Leetcode:First Missing Positive
- android List按时间排序
- 所谓幸福,从来没有答案
- 黑马程序员--Java面向对象——反射
- 虚拟机设置中的各种网络连接方式详解
- side effect
- leetcode: First Missing Positive
- win7 64 DLL的远程注入技术 及注入dll函数调用
- map形式的list集合,在struts标签中如何获取
- 谁败给了谁 - 博创OJ 1172 vector
- 黑马程序员--Java面向对象——JavaBean内省
- 软件测试中的八大浪费现象
- SharePoint开发中如何使用Visual Studio给你的Web Part添加图标
- 黑马程序员--Java面向对象——注解
- 东软实训(二)