LeetCode First Missing Positive
来源:互联网 发布:五五开黑历史知乎 编辑:程序博客网 时间:2024/06/05 00:33
题目
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.
从头向尾扫描,
如果数i在[1,n],且数i和编号为i-1的数不等,则交换两者。
处理一遍后,所有[1,n]的数在正确的位置上都有出现,
如果相应位置i-1上的数不是i,则数i是缺的,从头向后扫一次即可。
代码:
class Solution {public: int firstMissingPositive(int A[], int n) { int i=0;while(i<n)//交换元素到合适的位置{if(A[i]>0&&A[i]<=n&&A[i]!=i+1&&A[i]!=A[A[i]-1])swap(A[i],A[A[i]-1]);elsei++;}for(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
- CSDN博客之旅_记录技术学习的点滴_共筑技术王国
- C++String类关键操作简介
- Android系列教程之四:Android项目的目录结构
- 【暮色天】成功,需要耐心(6.12)
- 时间
- LeetCode First Missing Positive
- Swift学习笔记--关于Swift
- Android 内核源代码交叉编译
- MIT:算法导论——7.2.二叉树
- 解决X64操作系统PL/SQL连接报错问题 make sure you have the 32 bits oracle client installed
- Android控件TextView的实现原理分析
- 合并排序算法
- 《修改代码的艺术》迷你书
- Android4.4 状态栏信号和数据业务图片说明