高频算法题

两个长度相等的数组中寻找中位数(NC36d)
class Solution {
public:
    int findMedianinTwoSortedAray(vector<int>& arr1, vector<int>& arr2) {
        // write code here
        int n = arr1.size();
        if (n == 0) {
            return NULL;
        }
        int l1 = 0, r1 = n - 1;
        int l2 = 0, r2 = n -1;
        int mid1, mid2;
        //终止条件为l1 = r1
        while (l1 < r1) {
            mid1 = l1 + (r1 - l1) / 2;
            mid2 = l2 + (r2 - l2) / 2;
            int k = r1 - l1 + 1;
            if (arr1[mid1] == arr2[mid2]) {
                return arr1[mid1];
            }else if (arr1[mid1] > arr2[mid2]) {
                if (k % 2 == 0) {
                    r1 = mid1;
                    l2 = mid2 + 1;
                } else {
                    r1 = mid1;
                    l2 = mid2;
                }
            }else {
                if (k % 2 == 0) {
                    r2 = mid2;
                    l1 = mid1 + 1;
                }else {
                    l1 = mid1;
                    r2 = mid2;
                }
            }
        }
        return min(arr1[l1],arr2[l2]);
    }
};
class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        if (nums1.size() > nums2.size()) {
            return findMedianSortedArrays(nums2, nums1);
        }
        
        int m = nums1.size();
        int n = nums2.size();
        int left = 0, right = m;
        // median1:前一部分的最大值
        // median2:后一部分的最小值
        int median1 = 0, median2 = 0;

        while (left <= right) {
            // 前一部分包含 nums1[0 .. i-1] 和 nums2[0 .. j-1]
            // 后一部分包含 nums1[i .. m-1] 和 nums2[j .. n-1]
            int i = (left + right) / 2;
            int j = (m + n + 1) / 2 - i;

            // nums_im1, nums_i, nums_jm1, nums_j 分别表示 nums1[i-1], nums1[i], nums2[j-1], nums2[j]
            int nums_im1 = (i == 0 ? INT_MIN : nums1[i - 1]);
            int nums_i = (i == m ? INT_MAX : nums1[i]);
            int nums_jm1 = (j == 0 ? INT_MIN : nums2[j - 1]);
            int nums_j = (j == n ? INT_MAX : nums2[j]);

            if (nums_im1 <= nums_j) {
                median1 = max(nums_im1, nums_jm1);
                median2 = min(nums_i, nums_j);
                left = i + 1;
            } else {
                right = i - 1;
            }
        }

        return (m + n) % 2 == 0 ? (median1 + median2) / 2.0 : median1;
    }
};

正则表达式的匹配(nc122)
class Solution {
public:
    bool matchCore(string str, string pattern) {
        if (str[0] == '\0' && pattern[0] =='\0') {
            return true;
        }
        if(str[0] != '\0' && pattern[0] == '\0')
            return false;
        if (pattern[1] == '*') {
            if(pattern[0] == str[0] || (pattern[0] == '.' && str[0] != '\0')) {
                return matchCore(str.substr(1), pattern.substr(2)) ||
                    matchCore(str.substr(1), pattern) ||
                    matchCore(str, pattern.substr(2));
            } else{
                return matchCore(str, pattern.substr(2));
            }
        }
        if(pattern[0] == str[0] || (pattern[0] == '.' && str[0] != '\0'))
            return matchCore(str.substr(1), pattern.substr(1));
        return false;
    }
    bool match(string str, string pattern) {
        // write code here
        if (str.length() == 0 && pattern.length() == 0) {
            return true;
        }
        return matchCore(str, pattern);
    }
};
通配符匹配(NC44)
class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        int n = strlen(s),m = strlen(p);
        vector<vector<int>> dp(m +1,vector<int>(n+1));
        dp[0][0] = true;
        for (int i = 1; i<= m; i++) {
            dp[i][0] = dp[i - 1][0] && p[i-1] =='*';
            for (int j = 1; j <= n; j++) {
                if(p[i-1] == '*') 
                    dp[i][j] = dp[i-1][j] || dp[i][j-1]; //动态规划递推式(星号) 表示星号可以匹配0个(决定于上次外循环的结果)或者多个(决定于刚才内循环的结果)
                else 
                    dp[i][j] = dp[i-1][j-1] && (p[i-1]=='?' || s[j-1] == p[i-1]); //动态规划递推式(非星号) 表示dp值取决于上次的状态和当前状态
                
            }
        }
        return dp[m][n];
    }
};
二叉树的最大路径和
class Solution {
public:
    int maxval = INT_MIN;
    int traversal(TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        int leftval = root->val + traversal(root->left);
        int rightval = root->val + traversal(root->right);
        int left_right_root = leftval + rightval - root->val;
        maxval = max(max(max(max(leftval, rightval),left_right_root), root->val), maxval);
        return max(max(leftval, rightval),root->val);
    }
    int maxPathSum(TreeNode* root) {
        // write code here
        traversal(root);
        return maxval;
        
    }
};
树的直径
/**
 * struct Interval {
 *	int start;
 *	int end;
 * };
 */
class Solution {
public:
    int max_sum=0;
    int end=0;
    unordered_map<int, vector<pair<int, int>>> mp;
    void helper(int x, int sum, int prev) {
        int count = 0;
        for (int i = 0; i < mp[x].size(); i++) {
            if (mp[x][i].first != prev) {
                helper(mp[x][i].first, sum + mp[x][i].second, x);
                count++;
            }
        }
        if (count == 0 && max_sum < sum) {
            max_sum = sum;
            end = x;
        }
        return;
    }
    int solve(int n, vector<Interval>& Tree_edge, vector<int>& Edge_value) {
        for (int i = 0; i < Tree_edge.size(); i++) {
            mp[Tree_edge[i].start].push_back({Tree_edge[i].end, Edge_value[i]});
            mp[Tree_edge[i].end].push_back({Tree_edge[i].start, Edge_value[i]});
        }
        helper(0,0,-1);
        helper(end,0,-1);
        return max_sum;
    }
};
丢棋子
class Solution {
public:
    int traversal(int n, int k) {
        
        int min1 = INT_MAX;
        for(int i=1; i<=n; ++i){
            min1 = min(min1, max(traversal(i-1, k-1), traversal(n-i, k)));
        }
        return min1+1;
    }
    int solve(int n, int k) {
        // write code here
        if(n == 0) {
            return 0;
        }
        if (k == 1) {
            return n;
        }
        int logtimes = log2(n) + 1;
        if (k >= logtimes) {
            logtimes;
        }
        vector<int> f (k + 1, 0);
        int cnt = 0;
        while (f[k] < n) {
            ++cnt;
            for (int i = k; i > 0; --i) {
                f[i] += f[i - 1] + 1;
            }
        }
        return cnt;
    }
};
最长括号子串
class Solution {
public:
    int longestValidParentheses(string s) {
        vector<int> dp(s.size(), 0);
        int maxVal = 0;
        for (int i = 1; i < s.size(); i++) {
            if (s[i] == ')') {
                if (s[i - 1] == '(') {
                    dp[i] += 2;
                    if (i - 2 >= 0) {
                        dp[i] += dp[i - 2];
                    }
                } else if (dp[i - 1] > 0){
                    if ((i - dp[i - 1] - 1) >= 0 && s[i - dp[i - 1] - 1] == '(') {
                        dp[i] = dp[i - 1] + 2;
                        if ((i - dp[i - 1] - 2 >= 0)) {
                            dp[i] += dp[i - dp[i - 1] - 2];
                        }
                    }
                }
                maxVal = max(dp[i], maxVal);
            } 
        }
        return maxVal;
    }
};
最长回文子串
class Solution {public:    int getLongestPalindrome(string A, int n) {        int maxLen = 1;         vector<vector<bool>> dp(n, vector<bool>(n, false));        for (int i = n - 1; i >= 0; i--) {            for (int j = i; j < n; j++) {                if (A[i] == A[j]) {                    if (j - i <= 2) {                        dp[i][j] = true;                        maxLen = max(maxLen, j - i + 1);                    } else if (dp[i + 1][j - 1]) {                        dp[i][j] = true;                        maxLen = max(maxLen, j - i + 1);                    }                }            }        }        return maxLen;    }};
表达式求值(±*)
class Solution {public:    double cal_num(double num1, double num2, char c){        if (c == '+') {            return num1 + num2;        } else if (c == '-') {            return num1 - num2;        } else {            return num1 * num2;        }    }    int solve(string s) {        // write code here        stack<double> op;        stack<double> num;        int i = 0;        while (i < s.size()) {            if (s[i] >= '0' && s[i] <= '9') {                int k = 0;                while (i < s.size() && s[i] >= '0' && s[i] <= '9') {                    k = k * 10 + s[i++] - '0';                }                num.push(k);            } else {                if (s[i] == '(') {                    op.push(s[i]);                } else if (s[i] == ')') {                    while (op.top() != '(') {                        int num2 = num.top(); num.pop();                        int num1 = num.top(); num.pop();                        char c = op.top(); op.pop();                        num.push(cal_num(num1, num2, c));                    }                    op.pop();                } else if(s[i] == '*') {                    op.push(s[i]);                } else {                    while (num.size() >= 2) {                        if (op.top() == '(') break;                        int num2 = num.top(); num.pop();                        int num1 = num.top(); num.pop();                        char c = op.top(); op.pop();                        num.push(cal_num(num1, num2, c));                    }                    op.push(s[i]);                }                i++;            }        }        while (!op.empty()) {            int num2 = num.top(); num.pop();            int num1 = num.top(); num.pop();            char c = op.top(); op.pop();            num.push(cal_num(num1, num2, c));        }        return num.top();    }};
寻找数组中只出现一次的数字(其他均为k)
class Solution {public:    int foundOnceNumber(vector<int>& arr, int k) {        // write code here        int res = 0;        for (int i = 0; i < 32; i++) {            int sum = 0;            for (auto x : arr) {                sum += x >> i & 1;            }            res += (sum % k) << i;        }        return res;    }};
接雨水
class Solution {public:    long long maxWater(vector<int>& arr) {        int l = 0;        int r = arr.size() - 1;        int l_max = arr[l];        int r_max = arr[r];        long long res = 0;        while (l <= r) {            l_max = max(l_max, arr[l]);            r_max = max(r_max, arr[r]);            if (l_max < r_max) {                res += l_max - arr[l++];            } else {                res += r_max - arr[r--];            }        }        return res;    }};
求两个数组的最长公共子序列(NC92)
丑数
class Solution {public:    int GetUglyNumber_Solution(int index) {        if (index <= 0) return 0;        vector<int> res(index);        res[0] = 1;        int p2 = 0;        int p3 = 0;        int p5 = 0;        for (int i = 1; i < index; i++) {            res[i] = min(res[p2] * 2, min(res[p3] * 3, res[p5] * 5));            if (res[i] == res[p2] * 2) p2++;            if (res[i] == res[p3] * 3) p3++;            if (res[i] == res[p5] * 5) p5++;        }        return res[index- 1];    }};
链表中的节点每k个一组翻转(NC50)
/** * struct ListNode { *	int val; *	struct ListNode *next; * }; */class Solution {public:    /**     *      * @param head ListNode类      * @param k int整型      * @return ListNode类     */    ListNode* reverse(ListNode* head) {        ListNode* cur = head;        ListNode* pre = nullptr;        ListNode* next;        while (cur) {            next = cur->next;            cur->next = pre;            pre = cur;            cur = next;        }        return pre;    }    ListNode* reverseKGroup(ListNode* head, int k) {        // write code here        ListNode* dummy = new ListNode(-1);        dummy->next = head;        ListNode* start = head;        ListNode* end = head;        ListNode* next;        ListNode* pre = dummy;        while (end) {            for (int i = 0; i < k - 1; i++) {                end = end->next;                if (!end) {                    break;                }            }            if (!end) break;            next = end->next;            end->next = nullptr;            end = start;            start = reverse(start);                        pre->next = start;            end->next = next;            pre = end;            start = next;            end = start;        }        return dummy->next;    }};
求平方根NC32
删除链表中的第n个节点NC53
字符串出现次数的topk问题(NC97)
判断一个链表是否是回文结构(NC91)
class Solution {public:    bool isPail(ListNode* head) {        // write code here        if (!head && head->next) {            return true;        }        ListNode* slow = head;        ListNode* fast = head;        while (fast && fast->next) {            fast = fast->next->next;            slow = slow->next;        }        fast = slow->next;        slow->next = nullptr;        ListNode* nextNode;        while (fast) {            nextNode = fast->next;            fast->next = slow;            slow = fast;            fast = nextNode;        }        while (head && slow) {            if (head->val != slow->val) {                return false;            }            head = head->next;            slow = slow->next;        }        return true;    }};
求一个数组的最长递增子序列
class Solution {public:    vector<int> LIS(vector<int>& arr) {        // write code here        vector<int> res;        vector<int>maxLen;        res.push_back(arr[0]);        maxLen.push_back(1);        for (int i = 1; i < arr.size(); i++) {            if (arr[i] > res.back()) {                res.push_back(arr[i]);                maxLen.push_back(res.size());            } else {                int pos = lower_bound(res.begin(), res.end(), arr[i]) - res.begin();                res[pos] = arr[i];                maxLen.push_back(pos + 1);            }        }        int j = res.size();        for (int i = maxLen.size() - 1; j > 0; i--) {            if (maxLen[i] == j) {                res[--j] = arr[i];            }        }        return res;    }};
LRU缓存机制(NC93)
最长无重复子数组(NC41)
单链表的快速排序(NC70)
class Solution {public:    ListNode* partition(ListNode* start, ListNode* end) {        ListNode* p = start;        ListNode* q = p->next;        int val = start->val;        while (q != end) {            if (q->val < val) {                p = p->next;                swap(p->val, q->val);            }            q = q->next;        }        swap(p->val,start->val);        return p;            }    void quick_sort(ListNode* start, ListNode* end) {        if (start != end && start->next != end) {            ListNode* mid = partition(start, end);                        quick_sort(start, mid);            quick_sort(mid->next, end);        }    }    ListNode* sortInList(ListNode* head) {        // write code here        if (!head) {            return head;        }        quick_sort(head, nullptr);        return head;    }    };
二进制矩阵中的最短路径(从左上角到右下角)
class Solution {public:    using P = pair<int, int>;    int shortestPathBinaryMatrix(vector<vector<int>>& grid) {        int n = grid.size();        if (grid[0][0] || grid[n - 1][n - 1]) {            return -1;        }        const int dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};        queue<P> q;        q.push(P(0, 0));        grid[0][0] = 1;        int minlen = 1;        while (!q.empty()) {            int size = q.size();            for (int i = 0; i < size; i++) {                auto [x, y] = q.front(); q.pop();                if (x == n - 1 && y == n - 1) {                    return minlen;                }                for (int i = 0; i < 8; i++) {                    int nx = x + dir[i][0];                    int ny = y + dir[i][1];                    if (nx < 0 || ny < 0 || nx >= n || ny >= n || grid[nx][ny] == 1) continue;                    grid[nx][ny] = 1;                    q.push(P(nx, ny));                }            }            minlen++;        }        return -1;    }};
矩阵中的最长递增路径
class Solution {public:    vector<vector<int>> f;    int m, n;    int direct[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};    int solve(vector<vector<int> >& matrix) {        int res = 1;        m = matrix.size(); n = matrix[0].size();        f = vector<vector<int>>(m, vector<int>(n, -1));        for(int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                res = max(res, dfs(matrix, i, j));            }        }        return res;    }    int dfs(vector<vector<int>>& matrix, int x, int y) {        if(f[x][y] != -1) return f[x][y];        int ans = 1;        for (int i = 0; i < 4; i++) {            int newx = x+direct[i][0];            int newy = y+direct[i][1];            if(newx < 0 || newx >= m || newy < 0 || newy >= n) continue;            if(matrix[newx][newy] > matrix[x][y])                ans = max(ans, 1+dfs(matrix, newx, newy));        }        f[x][y] = ans;        return ans;    }};
二叉搜索树和双向链表
class Solution {public:    void ConvertCore(TreeNode* pRootOfTree, TreeNode** pLastList) {        if (pRootOfTree == nullptr) {            return;        }        ConvertCore(pRootOfTree->left, pLastList);        pRootOfTree->left = *pLastList;        if(*pLastList) {            (*pLastList)->right = pRootOfTree;        }        *pLastList = pRootOfTree;        ConvertCore(pRootOfTree->right, pLastList);    }    TreeNode* Convert(TreeNode* pRootOfTree) {        if (!pRootOfTree) {            return nullptr;        }        TreeNode* pLastList = nullptr;        ConvertCore(pRootOfTree, &pLastList);        TreeNode* pre = pLastList;        while (pre->left) {            pre = pre->left;        }        return pre;    }};
n皇后
class Solution {private:vector<vector<string>> result;// n 为输入的棋盘大小// row 是当前递归到棋牌的第几行了void backtracking(int n, int row, vector<string>& chessboard) {    if (row == n) {        result.push_back(chessboard);        return;    }    for (int col = 0; col < n; col++) {        if (isValid(row, col, chessboard, n)) { // 验证合法就可以放            chessboard[row][col] = 'Q'; // 放置皇后            backtracking(n, row + 1, chessboard);            chessboard[row][col] = '.'; // 回溯,撤销皇后        }    }}bool isValid(int row, int col, vector<string>& chessboard, int n) {    int count = 0;    // 检查列    for (int i = 0; i < row; i++) { // 这是一个剪枝        if (chessboard[i][col] == 'Q') {            return false;        }    }    // 检查 45度角是否有皇后    for (int i = row - 1, j = col - 1; i >=0 && j >= 0; i--, j--) {        if (chessboard[i][j] == 'Q') {            return false;        }    }    // 检查 135度角是否有皇后    for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {        if (chessboard[i][j] == 'Q') {            return false;        }    }    return true;}public:    vector<vector<string>> solveNQueens(int n) {        result.clear();        std::vector<std::string> chessboard(n, std::string(n, '.'));        backtracking(n, 0, chessboard);        return result;    }};
解数独
class Solution {private:bool backtracking(vector<vector<char>>& board) {    for (int i = 0; i < board.size(); i++) {        // 遍历行        for (int j = 0; j < board[0].size(); j++) { // 遍历列            if (board[i][j] != '.') continue;            for (char k = '1'; k <= '9'; k++) {     // (i, j) 这个位置放k是否合适                if (isValid(i, j, k, board)) {                     board[i][j] = k;                // 放置k                    if (backtracking(board)) return true; // 如果找到合适一组立刻返回                    board[i][j] = '.';              // 回溯,撤销k                }            }            return false;                           // 9个数都试完了,都不行,那么就返回false        }    }    return true; // 遍历完没有返回false,说明找到了合适棋盘位置了}bool isValid(int row, int col, char val, vector<vector<char>>& board) {    for (int i = 0; i < 9; i++) { // 判断行里是否重复        if (board[row][i] == val) {            return false;        }    }    for (int j = 0; j < 9; j++) { // 判断列里是否重复        if (board[j][col] == val) {            return false;        }    }    int startRow = (row / 3) * 3;    int startCol = (col / 3) * 3;    for (int i = startRow; i < startRow + 3; i++) { // 判断9方格里是否重复        for (int j = startCol; j < startCol + 3; j++) {            if (board[i][j] == val ) {                return false;            }        }    }    return true;}public:    void solveSudoku(vector<vector<char>>& board) {        backtracking(board);    }};
进制的转换(NC112)
class Solution {public:    string solve(int M, int N) {        // write code here        if (M == 0) {            return 0;        }        bool flag = false; // 记录是不是负数        if (M < 0) {            flag = true;            M = -M;        }        string res = "";        string jz = "0123456789ABCDEF";        while (M != 0) {            res += jz[M % N];            M /= N;        }        reverse(res.begin(), res.end());        if (flag) res.insert(0, "-");        return res;    }};
判断单链表是否是回文子串
class Solution {public:    bool isPail(ListNode* head) {        // write code here        ListNode* slow = head;        ListNode* fast = head;        while (fast && fast->next) {            fast = fast->next->next;            slow = slow->next;        }        fast = slow->next;        slow->next = nullptr;        while (fast) {            ListNode* next = fast->next;            fast->next = slow;            slow = slow->next;            fast = next;        }        while (head && slow) {            if (slow->val != head->val) {                return false;            }            head = head->next;            slow = slow->next;        }    return true;    }};
数组中未出现的最小整数
class Solution {public:    /**     * return the min number     * @param arr int整型vector the array     * @return int整型     */    int minNumberdisappered(vector<int>& arr) {        int num = 0;        for (auto a: arr) {            if (a > 0) {                num ^= a;            }        }        cout << num << endl;        for (int i = 1; i <= arr.size(); i++) {            num ^= i;        }        cout << num << endl;        return 0;        return num == 0? arr.size() + 1 : num;            }};
二叉树的最大路径和(NC6)
括号生成
class Solution {public:    vector<string> generateParenthesis(int n) {        vector<string> res;        generateParenthesisDFS(n, n, "", res);        return res;    }    void generateParenthesisDFS(int left, int right, string out, vector<string> &res) {        cout << out << endl;        if (left > right) return;        if (left == 0 && right == 0) {            res.push_back(out);        }                    else {            if (left > 0) generateParenthesisDFS(left - 1, right, out + '(', res);            if (right > 0) generateParenthesisDFS(left, right - 1, out + ')', res);        }    }};
序列化二叉树
/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*/class Solution {public:    void SerializeCore(TreeNode* root, string& str) {        if (!root) {            str += '#';            return;        }        str += to_string(root->val);        str += ',';        SerializeCore(root->left, str);        SerializeCore(root->right, str);        return;    }    char* Serialize(TreeNode *root) {            if (!root) {            return nullptr;        }        string str = "";        SerializeCore(root, str);        int size = str.size();        char* res = new char[size + 1];        for (int i = 0; i < size; i++) {            res[i] = str[i];        }        res[size] = '\0';        return res;    }    TreeNode* DeserializeCore(char** str) {        if (**str == '#') {            (*str)++;            return nullptr;        }        int num = 0;        while (**str != '\0' && **str != ',') {            num = num * 10 + (**str - '0');            (*str)++;        }        TreeNode* root = new TreeNode(num);        if (**str == '\0') {            return root;        } else {            (*str)++;        }        root->left = DeserializeCore(str);        root->right = DeserializeCore(str);        return root;    }    TreeNode* Deserialize(char *str) {        if (str == nullptr) {            return nullptr;        }        return DeserializeCore(&str);    }};
大数乘法
class Solution {public:    string solve(string s, string t) {        // write code here        if (s.empty() || t.size() == true) {            return "0";        }        int len1 = s.size();        int len2 = t.size();        string res(len1 + len2, '0');        //把值放在i+j+1中        for (int i = len1 - 1; i >= 0; i--) {            for (int j = len2 - 1; j >= 0; j--) {                int temp = (s[i] - '0') * (t[j] - '0') + (res[i + j + 1] - '0');                res[i + j + 1] = temp % 10 + '0';                res[i + j] = res[i + j] + temp / 10;            }        }        for (int i = 0; i < res.size(); i++) {            if (res[i] != '0') {                return res.substr(i);            }        }        return res;    }};
最小覆盖子串
class Solution {public:    string minWindow(string S, string T) {        // write code here        if (S.size() < T.size()) return "";        unordered_map<char, int> mp;        for (int i = 0; i < T.size(); i++) {            mp[T[i]]++;        }        int need = T.size();        int minlen = INT_MAX;        string res = "";        int i = 0;        int j = 0;        while (j < S.size()) {            if (mp[S[j]] > 0) {                need--;            }            mp[S[j]]--;            j++;            while (need == 0) {                if (minlen > j - i) {                    minlen = j - i;                    res = S.substr(i, minlen);                }                mp[S[i]]++;                if (mp[S[i]] > 0) {                    need++;                }                i++;            }         }        if (minlen != INT_MAX) {            return res;        }        return "";    }};
数组中1的个数(NC120)
class Solution {public:     int  NumberOf1(int n) {         int count = 0;         while (n) {             count++;             n = n & (n - 1);         }         return count;     }};
随时找到数据流中的中位数(NC131)
class Solution {public:    int n = 0;    //降序队列,大顶堆    priority_queue<int> small;    //升序队列 小顶堆    priority_queue<int, vector<int>,greater<int>> big;    vector<double> flowmedian(vector<vector<int> >& operations) {        // write code here        vector<double> res;        for (auto &c : operations) {            if (c[0] == 1) {                if (small.empty()) small.push(c[1]);                else if (c[1] <= small.top()) small.push(c[1]);                else {                    big.push(c[1]);                }                if (small.size() - big.size() == 2) big.push(small.top()), small.pop();                if (big.size() - small.size() == 2) small.push(big.top()), big.pop();                n++;            } else {                if (!n) {                    res.push_back(-1);                }                else if (n & 1) {                    res.push_back(big.size() > small.size() ? big.top() : small.top());                                    }                else {                    res.push_back(((long long)big.top() + small.top()) *0.5);                }                            }        }                return res;    }};
N皇后(NC39)
class Solution {public:    vector<vector<string> > solveNQueens(int n) {        vector<vector<string> > res;        vector<int> pos(n, -1);        solveNQueensDFS(pos, 0, res);        return res;    }    void solveNQueensDFS(vector<int> &pos, int row, vector<vector<string> > &res) {        int n = pos.size();        if (row == n) {            vector<string> out(n, string(n, '.'));            for (int i = 0; i < n; ++i) {                out[i][pos[i]] = 'Q';            }            res.push_back(out);        } else {            for (int col = 0; col < n; ++col) {                if (isValid(pos, row ,col)) {                    pos[row] = col;                    solveNQueensDFS(pos, row + 1, res);                    pos[row] = -1;                }            }        }    }    bool isValid(vector<int> &pos, int row, int col) {        for (int i = 0; i < row; ++i) {            if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {                return false;            }        }        return true;    }};
字典树的实现(NC124)
实现计算AUC的值

从计算概率的角度理解AUC:随机抽取一对样本(一个正样本, 一个负样本),然后用训练得到的分类器来对这这个样本进行预测,预测得到的正样本的概率大于负样本概率的概率。

from sklearn.metrics import roc_auc_scoreimport numpy as npdef calcAUC(labels, probs):    N = 0    P = 0    neg_prob = []    pos_prob = []    for _,i in enumerate(labels):        if (i == 1):            P += 1            pos_prob.append(probs[_])        else:            N += 1            neg_prob.append(probs[_])    number = 0    for pos in pos_prob:        for neg in neg_prob:            if (pos > neg):                number += 1            elif (pos == neg):                number += 0.5    return number / (N * P)y = np.array([1,0,0,0,1,0,1,0,])pred = np.array([0.9, 0.8, 0.3, 0.1,0.4,0.9,0.66,0.7])print('auc=',calcAUC(y,pred))print('roc_auc=',roc_auc_score(y,pred))
kmp算法(文本串s在t中出现了多少次)
class Solution {public:    int kmp(string S, string T) {        if (S.empty() || S.size() > T.size())            return 0;        int count = 0;        vector<int> next(S.size());        int j = 0;        next[0] = 0;        for (int i = 1; i < S.size(); i++) {            while (j > 0 && S[i] != S[j]) {                j  = next[j - 1];            }            if (S[i] ==S[j]) j++;            next[i] = j;        }        j = 0;        for (int i = 0; i < T.size(); i++) {            while (j > 0 && T[i] != S[j]) {                j = next[j -1];            }            if (T[i] ==S[j]) {                j++;            }            if(j == S.size()){                count++;                j = next[j-1];            }                    }        return count;    }};
旋转数组
vector<int> solve(int n, int m, vector<int>& a) {        if (!n || !m) return a;        m %= n;        reverse(a.begin(),a.end());        reverse(a.begin(), a.begin() + m);        reverse(a.begin() + m, a.end());        return a;    }
#include<iostream>#include<vector>#include<algorithm>using namespace std;int k, a;vector<vector<int>> cap(41, vector<int>(2));//节点能力数组,发送能力,存储能力int res;vector<int> dpfun(vector<int> pre, vector<int> cap) { int send1 = min(pre[0], cap[0]);//第一次发送的数据包量 int send2 = min(cap[0], pre[1] + cap[1]);//第二次发送的数据包量 if (pre[0] - cap[0] > 0) send2 = min(pre[0] - cap[0] + pre[1], send2);//如果缓存没存满,并且缓存大于0        else send2 = min(send2, pre[1]);        //缓存=0; vector<int> r = { send1,send2 }; return r;}int main() { cin >> k; vector<vector<int>> dp(k+1, vector<int>(2));//代表第i个节点发送的数据包数 char c; for (int i = 1; i <= k; i++) {  cin >> cap[i][0] >> c >> cap[i][1]; } cin >> a; dp[0][0] = a;//第0个节点第一次发送a dp[0][1] = 0;//第二次发送0; dp[1] = dpfun(dp[0], cap[1]); res = min(dp[0][0] + dp[0][1], dp[1][0] + dp[1][1]);//如果只有一个节点,那么选择是故障还是不故障多 if (k == 0) {  cout << a; } else {  for (int i = 2; i <= k; i++) {   vector<int> res1 = dpfun(dp[i - 1], cap[i]);//前一个点没有故障   vector<int> res2 = dpfun(dp[i - 2], cap[i]);//前一个点故障   dp[i] = res1[0] + res1[1] <= res2[0] + res2[1] ? res1 : res2;//选择值最小的方案  }  res = min(dp[k][0] + dp[k][1], dp[k - 1][0] + dp[k - 1][1]); } cout << res; return 0;}// 关注TechGuide! 大厂笔经面经闪电速递!
 set<string>ret; void dfs(unordered_map<string,set<string>>&s1,unordered_map<string,set<string>>&s2,string s) {     for(auto c:s2[s])     {         ret.insert(c);     }     for(auto c:s1[s])     {         dfs(s1,s2,c);     } } int main() { 	int n; 	cin>>n; 	unordered_map<string,set<string>> s1; 	unordered_map<string,set<string>> s2; 	for(int i=0;i<n;++i)    {        string a,b,c;        cin>>a>>b>>c;        if(b=="subClassOf")            s1[c].insert(a);        if(b=="instanceOf")            s2[c].insert(a);    }    string s;    cin>>s;    dfs(s1,s2,s);    if(ret.size()==0)    {        cout<<"empty"<<endl;    }    else    {        int n=ret.size();        for(auto c:ret)        {            if(n==1)            {                cout<<c<<endl;            }            else                cout<<c<<" ";            n--;        }    }    return 0; }

NC35最小编辑代价

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值