LeetCode: First Missing Positive
来源:互联网 发布:淘宝上的diy耳机 编辑:程序博客网 时间:2024/06/05 21:51
思路:将第 i 个正数存放在第i个位置,即 A[i] = i,这个过程需要扫描一遍,复杂度为O(n),然后就是遍历一遍检验,时间复杂度也是O(n),如果A[i] != i,则i是第一个消失的正数。注意的是因为n可能存在A[0]位置上面,如果A[0] = n,则消失的正数为 n + 1,否则就是 n。
code:
class Solution {public: void swap(int &a,int &b){ a ^= b; b ^= a; a ^= b; } int firstMissingPositive(int A[], int n) { int start = 0; while(start < n){ if(A[start] > 0 && A[start] != start && A[start] < n && A[start] != A[A[start]]){ swap(A[start],A[A[start]]); } else start++; } for(int i = 1;i < n;i++) if(A[i] != i) return i; return A[0] == n ? n+1 : n; }};
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
- JD 1421:Abor(概率统计)
- android framework中调用第三方的jar包
- Alpha-Beta搜索
- Linux下OK6410平台C和汇编混合编程
- ARP 协议
- LeetCode: First Missing Positive
- n个节点能组成多少种二叉树
- iOS7开发学习之路:No.10:XCode手动Clean资源文件,xib文件autolayout,对某个特定文件关闭ARC
- js判断是什么浏览器
- 【跟我一步一步学Struts2】——Action
- LevelDb 资料整理
- Android init.rc BOOTCLASSPATH
- JAVA基础 (二)反射 深入解析反射机制
- 工作日志2014-08-27