LeetCode First Missing Positive
来源:互联网 发布:bbs论坛数据库设计 编辑:程序博客网 时间:2024/06/18 18:11
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.
O(n) 时间,并且不能开辟数组。我们通过交换数组中的值,尽量使得A[i]=i+1,这样,当交换完后,再扫描一下数组,如果A[i]!=i+1,则i+1为第一个missing的正整数。
class Solution {public: int firstMissingPositive(int A[], int n) { if(n<=0)return 1; for(int i=0;i<n;i++){ if(A[i]>0&&A[i]<=n&&A[i]!=i+1&&A[A[i]-1]!=A[i]){ swap(A[i],A[A[i]-1]); i--; } } for(int i=0;i<n;i++){ if(A[i]!=i+1)return i+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
- OC学习9——Foundation框架(上)
- Lua和C程序通过一个堆栈交换数据
- 如何通过笔迹分析一个人的性格?
- virtualbox+centos下db2 9.7安装
- RS485、RS422、RS232中的RS指什么呢?
- LeetCode First Missing Positive
- 初识JAVA,对servlet的理解
- 线性规划与网络流24题之最小路径覆盖问题
- lua的堆栈(摘要)
- UIActionSheet关闭动画过程中调用delegate = nil 导致的内存泄露
- 适配器模式
- Building Plugins for iOS
- 用java的一个复制图片程序
- 简单获取数据库连接串