leetcode: First Missing Positive
来源:互联网 发布:kof98键盘优化版 编辑:程序博客网 时间:2024/06/07 20:47
这道题和之前做过的在O(n)时间查找长度为n的数组中是否存在重复元素的思路相似。 我们还是在O(n)时间内将每一个符合要求的数A[i] = i;那么置换过后出现过的n以内正数都会在其位置上,我们只需遍历一遍,找到A[i]!=i的输出即可。 要注意的是这样置换的话只能将1--n-1的数置换到其位置上,所以如果在1--n-1上都正确,我们要判断A[0]是否为n来确定输出n或是n+1。
public class Solution { public int firstMissingPositive(int[] A) { int len = A.length; if( len == 0 ) { return 1; } int st=0; while( st<len ) { if( A[st] == st ) { st++; continue; } if( A[st]>=0 && A[st]<len && A[A[st]] != A[st] ) { int tmp = A[st]; A[st] = A[A[st]]; A[tmp] = tmp; continue; } else { st++; } } for( int i=1;i<len;i++ ) { if( A[i] != i ) { return i; } } if( A[0] == len ) { return len+1; } return len; }}
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
- 用jad工具反编译eclipse中jar文件中的class文件
- JavaScript跨域总结与解决办法
- 关联多宝平台容器不支持这种初始化
- 隐藏DataGrid中的一列
- js中string转成json格式
- leetcode: First Missing Positive
- Android开发之数据存储与访问(3)-SQLite数据库
- 消息推送之百度云推送Android集成与使用方法
- ASE 进程为send sleep如何解决
- 微博上市让新浪又站上“浪尖”
- 执行Action前显示确认窗口
- LIBSVM 在matlab 2013添加 VS2013 c++编译器
- 超级下饭菜--金针菇日本豆腐
- XmlBeanDefinitionReader-----Spring源码解析 配置文件装载与解析