LeetCode_First Missing Positive
来源:互联网 发布:如何将ubuntu安装到u盘 编辑:程序博客网 时间:2024/06/01 18:27
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.
这类题目的思路一般都是复用原数组,并且将数组中的元素hash到原数组中,看过陈利仁老师所说的“元神归位法”,这道题目就很简单了。
以下是我的代码:
class Solution{public:int firstMissingPositive(int A[], int n){if(A==NULL || n<0) throw "Invalid Arguments!";if(n==0) return 1;int i = 0;// Find the smallest num Greater than 0.int minNum = INT_MAX;for(i=0; i<n; i++){if(A[i]<minNum&&A[i]>0){minNum = A[i];}}if(minNum>1||minNum<=0){return 1;}// Hash the num using A[i]-minNum.for(i=0; i<n; ){if((A[i]!=minNum+i)&& (A[i]>0)&& (A[i]<minNum+n)&& (A[A[i]-minNum]!=A[i])){swap(A,i,A[i]-minNum);}else{i++;}}for(i=0; i<n; i++){if(A[i]!=i+minNum){break;}}return (i+minNum);}private:void swap(int A[], int i, int j){int temp = A[i];A[i] = A[j];A[j] = temp;}};
0 0
- LeetCode_First Missing Positive
- leetcode_First Missing Positive
- leetCode_First Missing Positive
- Leetcode_first-missing-positive (updated c++ and python version)
- LeetCode: First Missing Positive
- LeetCode First Missing Positive
- LeetCode: First Missing Positive
- [Leetcode] First Missing Positive
- leetcode12: First Missing Positive
- First Missing Positive
- [LeetCode] First Missing Positive
- [Leetcode] First Missing Positive
- leetcode First Missing Positive
- LeetCode First Missing Positive
- [leetcode] first missing positive
- First Missing Positive
- LeetCode: First Missing Positive
- First Missing Positive
- 软考-程序设计语言基础(编译原理)
- 服务器 libevent源码深度剖析十
- git工作流指南:集中式工作流
- java的高新技术
- 服务器 libevent源码深度剖析十一
- LeetCode_First Missing Positive
- 服务器 libevent源码深度剖析十二
- git工作流指南:Pull Request工作流
- 深刻理解原类(metaclass)
- ACdream 1430 SETI 后缀自动机/后缀数组 不重叠子串的个数
- git工作流指南:功能分支工作流
- Powerbuilder数据窗口的edit.useellipsis属性
- git工作流指南:Forking工作流
- this练习