題目連接html
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 spacespa
尋找數組中缺失的最小正整數code
首先最容易想到的是:先對數組排序,而後在查找,可是這樣不知足線性時間要求。如下代碼oj仍是能經過的htm
class Solution { public: int firstMissingPositive(int A[], int n) { sort(A, A+n); int k = 1; for(int i = 0; i < n; i++) if(A[i] < k);//爲了處理小於1的數 或者 處理連續出現相同的數 else if(A[i] != k)return k; else k++; return k; } };
使用哈希表來記錄某個數字是否出現過(固然也可使用bitmap)。這樣的話空間複雜度和int的最大值有關blog
class Solution { public: int firstMissingPositive(int A[], int n) { unordered_set<int> uset; for(int i = 0; i < n; i++) if(A[i] > 0)uset.insert(A[i]); for(int i = 1; ;i++) if(uset.count(i) == 0)return i; } };
注意到大小爲n的數組,缺失的最小正整數必定在範圍[1,n+1]內,所以改進一下算法2,可使用大小爲n+1的哈希表。空間複雜度是O(n),不符合題意排序
class Solution { public: int firstMissingPositive(int A[], int n) { vector<int> hashtable(n+2, 0);//hashtable[i] = 1表示數字i出現過 for(int i = 0; i < n; i++) if(A[i] > 0 && A[i] <= n+1)hashtable[A[i]] = 1; for(int i = 1; i <= n+1; i++) if(hashtable[i] == 0)return i; } };
算法4ip
上述算法3中,咱們能夠用數組自己來充當哈希表。稍微變通一下,在遍歷數組的過程當中把數字 i 放在A[i-1]的位置。最後若是A[k] != k+1就說明k+1這個數字沒有出現過。因爲數組的大小是n,所以若是原始數組中的數字是1,2…n,則最後應該返回n+1。leetcode
還須要注意的是if中判斷條件:A[i] != A[A[i]-1];即若是某個位置A[i]已經放置了i+1或者數字A[i]即將要放入的位置(A[A[i]-1])本來就是A[i],則跳過。這樣能夠避免出現死循環(如數組[1,2]和[1,1]) 本文地址
class Solution { public: int firstMissingPositive(int A[], int n) { for(int i = 0; i < n; ) if(A[i] > 0 && A[i] <= n && A[i] != A[A[i]-1]) swap(A[i], A[A[i]-1]); else i++; for(int i = 0; i < n; i++) if(A[i] != i+1)return i+1; return n+1; } };
【版權聲明】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3770051.html