**一. 題目描述**
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.
**二. 題目分析**
該題的大意是給定一個未排序的數組,該數組可能包含零或正負數,要求找出第一個未出現的正數。例如`[1, 2, 0]`,由于第一個未出現的正整數是`3`,則返回`3`;`[3, 4, -1, 1]`第一個未出現的正整數是`2`,則返回`2`。算法要求在`O(n)`的時間復雜度及常數空間復雜度內完成。
一種方法是,先把數組里每個正整數從`i`位放到第`i-1`位上,這樣就形成了有序的序列,然后檢查每一下標`index`與當前元素值,就能知道當前下標所對應的正整數是否缺失,若缺失則返回下標`index + 1`即可。
**三. 示例代碼**
~~~
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int firstMissingPositive(vector<int>& nums)
{
int n = nums.size();
for (int i = 0; i < n; ++i)
{
int temp = 0;
while (i + 1 != nums[i] && nums[i] != nums[nums[i] - 1] && nums[i] > 0)
{
temp = nums[i];
nums[i] = nums[temp - 1];
nums[temp - 1] = temp;
}
}
for (int i = 0; i < n; ++i)
{
if (i + 1 != nums[i])
return i + 1;
}
return n + 1;
}
};
~~~
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016騰訊軟件開發筆試題)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契數列問題)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波蘭式的計算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和問題)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- 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
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching