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.
class Solution {
public:
int firstMissingPositive(int A[], int n) {
vector<bool> flag(n + 1, false);
for (int i = 0; i < n; ++i)
if (A[i] > 0 && A[i] <= n)
flag[A[i]] = true;
int ans = 1;
while (ans <= n) {
if (flag[ans] == false) break;
++ans;
}
return ans;
}
};
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
class Solution {
void inorder(TreeNode *root, vector<int> &vec) {
if (root == NULL) return;
vec.push_back(root->val);
inorder(root->left, vec);
inorder(root->right, vec);
}
public:
void flatten(TreeNode *root) {
vector<int> vec;
inorder(root, vec);
if (vec.size() == 0) return;
TreeNode *pre = root;
for (int i = 1; i < vec.size(); ++i) {
TreeNode *tmp = new TreeNode(vec[i]);
pre->right = tmp;
pre->left = NULL;
pre = tmp;
}
return;
}
};