LeetCode (F)
来源:互联网 发布:java简历工作内容 编辑:程序博客网 时间:2024/05/16 07:50
First Missing Positive
AC Rate: 546/2441
My SubmissionsGiven 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;}};
Flatten Binary Tree to Linked List
AC Rate: 669/2768
My SubmissionsGiven 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
click to show hints.
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;}};