First Missing Positive
来源:互联网 发布:淘宝上好看的包包店铺 编辑:程序博客网 时间:2024/06/07 07:23
Method 1: reference http://www.geeksforgeeks.org/find-the-smallest-positive-number-missing-from-an-unsorted-array/
First split the array into negative part and positive part.
The negative part can be ignored, while for the positive part, for each element i, if i<size, when we mark array[i-1] as negative, meaning that positive integer i has occurred.
after all marking, scan the array again to find the first positive place j, then j+1 is the first missing positive integer.
Code: (8ms AC)
class Solution {public: int firstMissingPositive(int A[], int n) { int positionStart = split(A, n); return findFirstMissing(A+positionStart, n-positionStart); } int findFirstMissing(int A[], int size) { for(int i=0; i<size; i++) { if(abs(A[i])-1 < size && A[abs(A[i])-1] > 0) A[abs(A[i])-1] = -A[abs(A[i])-1]; } for(int i=0; i<size; i++) if(A[i] > 0) return i+1; return size+1; } int split(int A[], int size) { int j=0; for(int i=0; i<size; i++) { if(A[i] <= 0) { swap(A+i, A+j); j++; } } return j; } void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; }};
Method 2: use bucket sort. refer leetcode solution.
for each index i, if A[i] not equals i+1, then swap A[i] with A[ A[i]-1 ] until A[i] exceeds the array range or A[i] == A[ A[i]-1 ]
code: (40ms AC)
class Solution {public: int firstMissingPositive(int A[], int n) { bucket_sort(A, n); for(int i=0; i<n; i++) if(A[i] != i+1) return i+1; return n+1; } void bucket_sort(int A[], int n) { for(int i=0; i<n; i++) { while(A[i] != i+1) { if(A[i] <= 0 || A[i] > n || A[i] == A[A[i]-1]) break; swap(A+i, A+A[i]-1); } } } void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; }};
0 0
- 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
- First Missing Positive
- [LeetCode]First Missing Positive
- First Missing Positive
- First Missing Positive
- jquery easyui dialog问题
- Linux套接字编程
- Matlab做PCA分析
- 《LoadRunner 没有告诉你的》和《JMeter从入门到精通》
- Linux监控系统CPU、内存、磁盘空间和网口收发脚本
- First Missing Positive
- unity3d优化总结
- SSH之hibernate——get和load方法的区别
- DB2:有关"ERRORCODE=-4499, SQLSTATE=08001"详解
- C++Builder中使用MSCOMM进行串口编程
- Linux常用命令和VI命令
- Node.js实现的BigPipe
- 关于面向对象的理解
- Java 5种字符串拼接方式性能比较。