[leetcode]First Missing Positive
来源:互联网 发布:电脑写字板软件下载 编辑:程序博客网 时间:2024/06/16 12:15
问题描述:
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.
基本思路:
找到第一个没有出现的正整数。
把出现的正整数数值放到与下标一致的位置,至于非正整数出现的位置和重复正整数放置的位置,我们不管。再判断什么位置最先出现不连续的数值,就是答案了
代码:
int firstMissingPositive(int A[], int n) { //C++ for(int i = 0; i< n; i++) { if(i == A[i]-1) continue; int j = i; while(A[j] > 0 && A[j] <= n) { if(A[j] == A[A[j]-1]) break; int tmp = A[A[j]-1]; A[A[j]-1] = A[j]; A[j] = tmp; } } int p; for(p = 0; p< n; p++) if(A[p] != p+1) return p+1; if(p == n) return n+1; else return 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
- Nodejs学习路线图
- 第十三周 项目五--字符串操作(1.4)字母统计
- Nginx的安装与配置(Centos6.3)
- javascript闭包的理解
- 快速排序算法代码
- [leetcode]First Missing Positive
- POJ1745——Divisibility
- s3c6410裸机学习笔记(一)--汇编启动代码start.S
- 知识产权培训记录
- WIN7 Wireshark: There are no interfaces on which a capture can be done
- 内容观察者(ContentObserver)的使用~
- 'mysql' 不是内部或外部命令,也不是可运行的程序,或批处理文件。
- Android 知识图谱
- 第十三周 项目5:统计字符串中大小写字母的个数