LeetCode 40. First Missing Positive
来源:互联网 发布:内乡王登科网络诈骗 编辑:程序博客网 时间:2024/06/06 16:46
要求用O(n)时间,常数空间解题。所以不能快排(nlogn)。
注意到,对于A[i]>0 && A[i]<=n的那些数,在数组中若都最终满足A[i] == i+1, 那么只需最后遍历数组,找到第一个不满足A[i] == i+1的数,返回i+1即可。
因此遍历数组,在每次下标为i的迭代中,若A[i]>0 && A[i]<=n && A[i]!=i+1 && A[i]!=A[A[i]-1], 就不断地swap(A[i], A[A[i]-1]);
约束条件A[i] != A[A[i]-1]是为了处理输入为[1, 1]的情况,若没有这个条件,则在迭代到i=1时会陷入死循环。
代码:
class Solution {public: int firstMissingPositive(int A[], int n) { for (int i = 0; i < n; ++ i) { while (A[i]>0 && A[i]<=n && A[i]-1!=i && A[A[i]-1]!=A[i]) { swap(A[i], A[A[i]-1]); } } for (int i = 0; i < n; ++ i) { if (A[i]-1 != i ) { return i + 1; } } return n+1; }};
0 0
- LeetCode 40. 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
- java在命令提示符里运行
- 统计字符串A 在字符串B出现的个数
- UVa 10194 - Football (aka Soccer)
- ubuntu 安装maven提示出错 The program 'mvn' can be found in the following packages
- iOS开发常用国外网站清单
- LeetCode 40. First Missing Positive
- Java基本數據類型 長度和表示範圍
- 最新版的IOS真机测试教程
- Machine Learning Week 2 Linear Regression with multiple variables in Matlab or Octave
- 数组指针和指针数组的区别
- 链队的基本操作实现及约瑟夫环问题的队列解法
- 大数据量、高并发的数据库优化
- 量渡茄昧现守独崭伊费盅屏党袒了
- 卜巢奈让涸还藏卤确爬缎牙馅锌赋