# First Missing Positive
### Source
- leetcode: [First Missing Positive | LeetCode OJ](https://leetcode.com/problems/first-missing-positive/)
- lintcode: [(189) First Missing Positive](http://www.lintcode.com/en/problem/first-missing-positive/)
~~~
Given an unsorted integer array, find the first missing positive integer.
Example
Given [1,2,0] return 3, and [3,4,-1,1] return 2.
Challenge
Your algorithm should run in O(n) time and uses constant space.
~~~
### 題解
容易想到的方案是先排序,然后遍歷求得缺的最小整數。排序算法中常用的基于比較的方法時間復雜度的理論下界為 O(nlogn)O(n \log n)O(nlogn), 不符題目要求。常見的能達到線性時間復雜度的排序算法有 [基數排序](http://zh.wikipedia.org/wiki/%E5%9F%BA%E6%95%B0%E6%8E%92%E5%BA%8F),[計數排序](http://algorithm.yuanbin.me/zh-cn/basics_sorting/counting_sort.html) 和 [桶排序](http://algorithm.yuanbin.me/zh-cn/basics_sorting/bucket_sort.html)。
基數排序顯然不太適合這道題,計數排序對元素落在一定區間且重復值較多的情況十分有效,且需要額外的 O(n)O(n)O(n) 空間,對這道題不太合適。最后就只剩下桶排序了,桶排序通常需要按照一定規則將值放入桶中,一般需要額外的 O(n)O(n)O(n) 空間,咋看一下似乎不太適合在這道題中使用,但是若能設定一定的規則原地交換原數組的值呢?這道題的難點就在于這種規則的設定。
設想我們對給定數組使用桶排序的思想排序,第一個桶放1,第二個桶放2,如果找不到相應的數,則相應的桶的值不變(可能為負值,也可能為其他值)。
那么怎么才能做到原地排序呢?即若 A[i]=xA[i] = xA[i]=x, 則將 x 放到它該去的地方 - A[x?1]=xA[x - 1] = xA[x?1]=x, 同時將原來 A[x?1]A[x - 1]A[x?1] 地方的值交換給 A[i]A[i]A[i].
排好序后遍歷桶,如果不滿足 f[i]=i+1f[i] = i + 1f[i]=i+1, 那么警察叔叔就是它了!如果都滿足條件怎么辦?那就返回給定數組大小再加1唄。
### C++
~~~
class Solution {
public:
/**
* @param A: a vector of integers
* @return: an integer
*/
int firstMissingPositive(vector<int> A) {
const int size = A.size();
for (int i = 0; i < size; ++i) {
while (A[i] > 0 && A[i] <= size && \
(A[i] != i + 1) && (A[i] != A[A[i] - 1])) {
int temp = A[A[i] - 1];
A[A[i] - 1] = A[i];
A[i] = temp;
}
}
for (int i = 0; i < size; ++i) {
if (A[i] != i + 1) {
return i + 1;
}
}
return size + 1;
}
};
~~~
### 源碼分析
核心代碼為那幾行交換,但是要很好地處理各種邊界條件則要下一番功夫了,要能正常的交換,需滿足以下幾個條件:
1. `A[i]` 為正數,負數和零都無法在桶中找到生存空間...
1. `A[i] \leq size` 當前索引處的值不能比原數組容量大,大了的話也沒用啊,肯定不是缺的第一個正數。
1. `A[i] != i + 1`, 都滿足條件了還交換個毛線,交換也是自身的值。
1. `A[i] != A[A[i] - 1]`, 避免欲交換的值和自身相同,否則有重復值時會產生死循環。
如果滿足以上四個條件就可以愉快地交換彼此了,使用`while`循環處理,此時`i`并不自增,直到將所有滿足條件的索引處理完。
注意交換的寫法,若寫成
~~~
int temp = A[i];
A[i] = A[A[i] - 1];
A[A[i] - 1] = temp;
~~~
這又是滿滿的 bug :( 因為在第三行中`A[i]`已不再是之前的值,第二行賦值時已經改變,故源碼中的寫法比較安全。
最后遍歷桶排序后的數組,若在數組大小范圍內找到不滿足條件的解,直接返回,否則就意味著原數組給的元素都是從1開始的連續正整數,返回數組大小加1即可。
### 復雜度分析
「桶排序」需要遍歷一次原數組,考慮到`while`循環也需要一定次數的遍歷,故時間復雜度至少為 O(n)O(n)O(n). 最后求索引值最多遍歷一次排序后數組,時間復雜度最高為 O(n)O(n)O(n), 用到了`temp`作為中間交換變量,空間復雜度為 O(1)O(1)O(1).
### Reference
- [Find First Missing Positive | N00tc0d3r](http://n00tc0d3r.blogspot.com/2013/03/find-first-missing-positive.html)
- [LeetCode: First Missing Positive 解題報告 - Yu's Garden - 博客園](http://www.cnblogs.com/yuzhangcmu/p/4200096.html)
- [First Missing Positive | 九章算法](http://www.jiuzhang.com/solutions/first-missing-positive/)
- Preface
- Part I - Basics
- Basics Data Structure
- String
- Linked List
- Binary Tree
- Huffman Compression
- Queue
- Heap
- Stack
- Set
- Map
- Graph
- Basics Sorting
- Bubble Sort
- Selection Sort
- Insertion Sort
- Merge Sort
- Quick Sort
- Heap Sort
- Bucket Sort
- Counting Sort
- Radix Sort
- Basics Algorithm
- Divide and Conquer
- Binary Search
- Math
- Greatest Common Divisor
- Prime
- Knapsack
- Probability
- Shuffle
- Basics Misc
- Bit Manipulation
- Part II - Coding
- String
- strStr
- Two Strings Are Anagrams
- Compare Strings
- Anagrams
- Longest Common Substring
- Rotate String
- Reverse Words in a String
- Valid Palindrome
- Longest Palindromic Substring
- Space Replacement
- Wildcard Matching
- Length of Last Word
- Count and Say
- Integer Array
- Remove Element
- Zero Sum Subarray
- Subarray Sum K
- Subarray Sum Closest
- Recover Rotated Sorted Array
- Product of Array Exclude Itself
- Partition Array
- First Missing Positive
- 2 Sum
- 3 Sum
- 3 Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Merge Sorted Array
- Merge Sorted Array II
- Median
- Partition Array by Odd and Even
- Kth Largest Element
- Binary Search
- Binary Search
- Search Insert Position
- Search for a Range
- First Bad Version
- Search a 2D Matrix
- Search a 2D Matrix II
- Find Peak Element
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array II
- Median of two Sorted Arrays
- Sqrt x
- Wood Cut
- Math and Bit Manipulation
- Single Number
- Single Number II
- Single Number III
- O1 Check Power of 2
- Convert Integer A to Integer B
- Factorial Trailing Zeroes
- Unique Binary Search Trees
- Update Bits
- Fast Power
- Hash Function
- Count 1 in Binary
- Fibonacci
- A plus B Problem
- Print Numbers by Recursion
- Majority Number
- Majority Number II
- Majority Number III
- Digit Counts
- Ugly Number
- Plus One
- Linked List
- Remove Duplicates from Sorted List
- Remove Duplicates from Sorted List II
- Remove Duplicates from Unsorted List
- Partition List
- Two Lists Sum
- Two Lists Sum Advanced
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle II
- Reverse Linked List
- Reverse Linked List II
- Merge Two Sorted Lists
- Merge k Sorted Lists
- Reorder List
- Copy List with Random Pointer
- Sort List
- Insertion Sort List
- Check if a singly linked list is palindrome
- Delete Node in the Middle of Singly Linked List
- Rotate List
- Swap Nodes in Pairs
- Remove Linked List Elements
- Binary Tree
- Binary Tree Preorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Postorder Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Maximum Depth of Binary Tree
- Balanced Binary Tree
- Binary Tree Maximum Path Sum
- Lowest Common Ancestor
- Invert Binary Tree
- Diameter of a Binary Tree
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Subtree
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Serialization
- Binary Search Tree
- Insert Node in a Binary Search Tree
- Validate Binary Search Tree
- Search Range in Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Binary Search Tree Iterator
- Exhaustive Search
- Subsets
- Unique Subsets
- Permutations
- Unique Permutations
- Next Permutation
- Previous Permuation
- Unique Binary Search Trees II
- Permutation Index
- Permutation Index II
- Permutation Sequence
- Palindrome Partitioning
- Combinations
- Combination Sum
- Combination Sum II
- Minimum Depth of Binary Tree
- Word Search
- Dynamic Programming
- Triangle
- Backpack
- Backpack II
- Minimum Path Sum
- Unique Paths
- Unique Paths II
- Climbing Stairs
- Jump Game
- Word Break
- Longest Increasing Subsequence
- Palindrome Partitioning II
- Longest Common Subsequence
- Edit Distance
- Jump Game II
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Distinct Subsequences
- Interleaving String
- Maximum Subarray
- Maximum Subarray II
- Longest Increasing Continuous subsequence
- Longest Increasing Continuous subsequence II
- Graph
- Find the Connected Component in the Undirected Graph
- Route Between Two Nodes in Graph
- Topological Sorting
- Word Ladder
- Bipartial Graph Part I
- Data Structure
- Implement Queue by Two Stacks
- Min Stack
- Sliding Window Maximum
- Longest Words
- Heapify
- Problem Misc
- Nuts and Bolts Problem
- String to Integer
- Insert Interval
- Merge Intervals
- Minimum Subarray
- Matrix Zigzag Traversal
- Valid Sudoku
- Add Binary
- Reverse Integer
- Gray Code
- Find the Missing Number
- Minimum Window Substring
- Continuous Subarray Sum
- Continuous Subarray Sum II
- Longest Consecutive Sequence
- Part III - Contest
- Google APAC
- APAC 2015 Round B
- Problem A. Password Attacker
- Microsoft
- Microsoft 2015 April
- Problem A. Magic Box
- Problem B. Professor Q's Software
- Problem C. Islands Travel
- Problem D. Recruitment
- Microsoft 2015 April 2
- Problem A. Lucky Substrings
- Problem B. Numeric Keypad
- Problem C. Spring Outing
- Microsoft 2015 September 2
- Problem A. Farthest Point
- Appendix I Interview and Resume
- Interview
- Resume