vector<int>topK(vector<int> input,int k){
priority_queue<int> min;
vector<int> res;for(int i =0; i < input.size(); i++){
min.push(input[i]);if(min.size()> k)min.pop();}while(!min.empty()){
res.push_back(min.top());
min.pop();}return res;}
7. 反转链表
ListNode*reverseList(ListNode* head){
ListNode* pre = nullptr;auto cur = head;while(cur){auto next = cur->next;
cur->next = pre;
pre = cur;
cur = next;}return pre
}
class UnionFind {
public:
vector<int> father;UnionFind(int num){//将连通域的父亲置为其下标for(int i =0; i < num; i++)father.push_back(i);}intFind(int n){//查找每个元素的当前连通域while(father[n]!= n)n = father[n];return n;}voidUnion(int a,int b){//将当前元素加入到连通域int fa =Find(a);int fb =Find(b);
father[fb]= fa;}
bool JudgeUnion(int a,int b){//判断当前元素是否在同一个连通域int fa =Find(a);int fb =Find(b);
bool res = fa == fb;
father[fb]= fa;return res;}};
10. 二叉树的公共祖先
struct TreeNode {int val;
TreeNode* left;
TreeNode* right;TreeNode(int x):val(x),left(NULL),right(NULL){}};
class Solution {
public:
TreeNode*lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){if(!root)returnNULL;if(root == p || root == q)return root;auto left =lowestCommonAncestor(root->left, p, q);auto right =lowestCommonAncestor(root->right, p, q);if(left && right)return root;if(left)return left;return right;}};
11. 二叉树的遍历
struct TreeNode {int val;
TreeNode* left;
TreeNode* right;TreeNode(int x):val(x),left(NULL),right(NULL){}};
class Solution {
public:
vector<int>inorderTraversal(TreeNode* root){//中序遍历
vector<int> v;
stack<TreeNode*> s;
TreeNode* now = root;while(now ||!s.empty());{while(now){
s.push(now);
now = now->left;}if(!s.empty()){
now = s.top();
s.pop();
v.push_back(now->val);
now = now->right;}}return v;}};
12. N个骰子出现和为m的几率
constint N =100;int f[N][N *6];intmain(){int n, m;
cin >> n >> m;
f[0][0]=1;for(int i =1; i <=10; i++)for(int j = i; j <= m; j++)//这里的J范围:当只有一个骰子的时候(1~6)两个骰子(2~12)...n个骰子(n~6n)for(int k =1; k <=6; k++)if(j - k >=0)f[i][j]+= f[i -1][j - k];double p = f[n][m]/pow(6, n);
cout << p;return0;}
13. 寻找两个链表相交的位置
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB){auto p = headA, q = headB;while(p != q){if(p) p = p->next;else p = headB;if(q) q = q->next;else q = headA;}return p;}