剑指offer(21-40)_leetcode

21. 剑指 Offer 22 链表中倒数第k个节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
    
    
        ListNode *p = head;
        int count = 0;
        while (p) {
    
    
            ++count;
            p = p->next;
        }
        if (k > count) {
    
    
            return nullptr;
        }
        p = head;
        for (int i = 0; i < count - k; i++) {
    
    
            p = p->next;
        }
        return p;
    }
};


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
    
    
        //双指针
        ListNode *fast = head;
        ListNode *slow = head;
        for (int i = 0; i < k; i++) {
    
    
            fast = fast->next;
        }
        while (fast) {
    
    
            fast = fast->next;
            slow = slow->next;
        }
        return slow;
    }
};

22. 剑指 Offer 24 反转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        ListNode *temp;
        ListNode *cur = head;
        ListNode *pre = nullptr;
        while (cur) {
    
    
            temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

23. 剑指 Offer 25 合并两个排序的链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    
    
        if (!l1) return l2;
        else if (!l2) return l1;

        ListNode *res = nullptr;
        if (l1->val < l2->val) {
    
    
            res = l1;
            res->next = mergeTwoLists(l1->next, l2);
        }
        if (l1->val >= l2->val) {
    
    
            res = l2;
            res->next = mergeTwoLists(l1, l2->next);
        }
        return res;
    }
};

24. 剑指 Offer 26 树的子结构

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    bool recur(TreeNode* A, TreeNode* B) {
    
    
        if (B == nullptr) return true;
        if (A == nullptr || A->val != B->val) return false;
        return recur(A->left, B->left) && recur(A->right, B->right); 
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
    
    
        //两树其中一个为空时 直接返回false
        if (A == nullptr || B == nullptr) return false;

        return recur(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B);
    }
};

25. 剑指 Offer 27 二叉树的镜像

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    TreeNode* mirrorTree(TreeNode* root) {
    
    
        if (!root) return nullptr;
        swap(root->left, root->right);

        mirrorTree(root->left);
        mirrorTree(root->right);
        return root;
    }
};

26. 剑指 Offer 28 对称的二叉树

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    bool isSymmetric(TreeNode* root) {
    
    
        if (!root) return true;

        return dfs(root->left, root->right);
    }
    bool dfs(TreeNode* left, TreeNode* right) {
    
    
        if (!left && !right) return true;
        if (!left || !right) return false;
        if (left->val != right->val) return false;

        return dfs(left->left, right->right) && dfs(left->right, right->left);
    }
};

27. 剑指 Offer 29 顺时针打印矩阵

class Solution {
    
    
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
    
    
        if (matrix.empty()) return {
    
    };
        vector<int> res;
        int l = 0;
        int r = matrix[0].size() - 1;
        int u = 0;
        int d = matrix.size() - 1;
        while (true) {
    
    
            for (int i = l; i <= r; i++) {
    
    
                res.push_back(matrix[u][i]);
            }
            if (++u > d) break;
            for (int i = u; i <= d; i++) {
    
    
                res.push_back(matrix[i][r]);
            }
            if (--r < l) break;
            for (int i = r; i >= l; i--) {
    
    
                res.push_back(matrix[d][i]);
            }
            if (--d < u) break;
            for (int i = d; i >= u; i--) {
    
    
                res.push_back(matrix[i][l]);
            }
            if (++l > r) break;
        }
        return res;
    }
};


28. 剑指 Offer 30 包含min函数的栈

class MinStack {
    
    
public:
    stack<int> st;
    stack<int> minStack;
    /** initialize your data structure here. */
    //构造函数清空栈容器
    MinStack() {
    
    
        while(!st.empty()) {
    
    
            st.pop();
        }
        while (!minStack.empty()) {
    
    
            minStack.pop();
        }
        //初始化最小栈的栈顶元素为最大值,为了防止top访问空指针报错
        minStack.push(INT_MAX);
    }
    
    void push(int x) {
    
    
        st.push(x);
        int minval =  std::min(minStack.top(), x);
        minStack.push(minval);
    }
    
    void pop() {
    
    
        st.pop();
        minStack.pop();
    }
    
    int top() {
    
    
        return st.top();
    }
    
    int min() {
    
    
        return minStack.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(x);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->min();
 */

29. 剑指 Offer 31 栈的压入、弹出序列

class Solution {
    
    
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
    
    
        stack<int> st; //辅助栈
        int cur = 0;  //弹出序列中的当前元素
        for (int i = 0; i < pushed.size(); i++) {
    
    
            st.push(pushed[i]); // 入栈操作
            while (!st.empty() && st.top() == popped[cur]) {
    
    
                st.pop(); //出栈操作
                ++cur;
            }
        }
        return st.empty();
    }
};

30. 剑指 Offer 32 - I 从上到下打印二叉树

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<int> levelOrder(TreeNode* root) {
    
    
        //层序遍历
        queue<TreeNode*> que;
        if (root != nullptr) que.push(root);
        vector<int> res;
        while (!que.empty()) {
    
    
            int size = que.size();
            for (int i = 0; i < size; i++) {
    
    
                TreeNode* node = que.front();
                que.pop();
                res.push_back(node->val);
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return res;
    }
};

31. 剑指 Offer 32 - II 从上到下打印二叉树 II

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
    
    
        queue<TreeNode*> que;
        if (root != nullptr) que.push(root);
        vector<vector<int>> res;
        while (!que.empty()) {
    
    
            int size = que.size();
            vector<int> vec;
            for (int i = 0; i < size; i++) {
    
    
                TreeNode* node = que.front();
                que.pop();
                vec.push_back(node->val);
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
            res.push_back(vec);
        }
        return res;
    }
};

32. 剑指 Offer 32 - III 从上到下打印二叉树 III

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
    
    
        queue<TreeNode*> que;
        if (root != nullptr) que.push(root);
        vector<vector<int>> res;
        int level = 0;
        while (!que.empty()) {
    
    
            int size = que.size();
            vector<int> vec;
            for (int i = 0; i < size; i++) {
    
    
                TreeNode* node = que.front();
                que.pop();
                vec.push_back(node->val);
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
            if (level++ % 2 == 1)
                reverse(vec.begin(), vec.end());
            res.push_back(vec);

        }
        return res;
    }
};

33. 剑指 Offer 33 二叉搜索树的后序遍历序列

class Solution {
    
    
public:
    bool devide_and_rule(int left, int right, vector<int>& postorder) {
    
    
        if (left >= right) return true; //当树的节点数为1, 返回true

        int root = postorder[right];

        int i = right - 1;
        while (i >= 0 && root < postorder[i]) --i;
        int mid = i; //mid为左字树的right;
        while (i >= 0 && root > postorder[i]) --i;

        if (i >= 0) return false; //i >= 0 说明不满足二叉搜索树的性质

        return devide_and_rule(left, mid, postorder) && devide_and_rule(mid + 1, right - 1, postorder);
    }
    bool verifyPostorder(vector<int>& postorder) {
    
    
        //递归
        if (postorder.empty()) return true;
        return devide_and_rule(0, postorder.size() - 1, postorder);
    }
};

34. 剑指 Offer 34 二叉树中和为某一值的路径

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    
    
public:
    vector<vector<int>> res;
    vector<int> path;
    void recur(TreeNode* root, int target) {
    
    
        if (root == nullptr) return ;
        path.push_back(root->val);
        target -= root->val;
        if (target == 0 && root->left == nullptr && root->right == nullptr) {
    
    
            res.push_back(path);
        }
        recur(root->left, target);
        recur(root->right, target);
        //走到最后一个节点不满足,一个一个的进行pop
        path.pop_back();
    }
    vector<vector<int>> pathSum(TreeNode* root, int target) {
    
    
        recur(root, target);
        return res;
    }
};

35. 剑指 Offer 35 复杂链表的复制

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
    
    
public:
    Node* copyRandomList(Node* head) {
    
    
        //哈系表
        if (head == nullptr) return nullptr;
        Node* cur = head;
        unordered_map<Node*, Node*> map;
        //复制各节点,并建立原节点到新节点的映射
        while (cur != nullptr) {
    
    
            map[cur] = new Node(cur->val);
            cur = cur->next;
        }
        cur = head;
        //构建新链表的next random指向
        while (cur != nullptr) {
    
    
            map[cur]->next = map[cur->next];
            map[cur]->random = map[cur->random];
            cur = cur->next;
        }
        //返回新链表的头节点
        return map[head];
    }
};

36. 剑指 Offer 36 二叉搜索树与双向链表

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
    
    
public:
    Node *pre, *head;
    void dfs(Node* cur) {
    
    
        if (cur == nullptr) return;
        dfs(cur->left);
        if (pre != nullptr) pre->right = cur;
        else head = cur;
        cur->left = pre;
        pre = cur;
        dfs(cur->right);
    }
    Node* treeToDoublyList(Node* root) {
    
    
        if (root == nullptr) return nullptr;
        dfs(root);
        head->left = pre;
        pre->right = head;
        return head;
    }
};

37. 剑指 Offer 37 序列化二叉树

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
    
    
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
    
    
        //bfs
        string res;
        if (!root) return res;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
    
    
            TreeNode* front = q.front();
            q.pop();
            if (front) {
    
    
                res += to_string(front->val) + ',';
                q.push(front->left);
                q.push(front->right);
            } else {
    
    
                res += "null,";
            }
            
            
        }
        return res.substr(0, res.size() - 1);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
    
    
        if (data.empty()) return nullptr;
        vector<string> s = split(data);

        queue<TreeNode*> q;
        TreeNode* root = new TreeNode(stoi(s[0]));
        q.push(root);
        int i = 1;

        while (!q.empty()) {
    
    
            TreeNode* front = q.front();
            q.pop();
            if (s[i] != "null") {
    
    
                front->left = new TreeNode(stoi(s[i]));
                q.push(front->left);
            }
            ++i;
            if (s[i] != "null") {
    
    
                front->right = new TreeNode(stoi(s[i]));
                q.push(front->right);
            }
            ++i;
        }    
        return root;
    }

    vector<string> split(string& s) {
    
    
        vector<string> res;
        int n = s.size();
        int i = 0;
        while (i < n) {
    
    
            int j = i + 1;
            while (j < n && s[j] != ',') ++j;
            res.push_back(s.substr(i, j - i));
            i = j + 1;
        }
        return res;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

38. 剑指 Offer 38 字符串的排列

class Solution {
    
    
public:
    vector<string> res;
    void dfs(string s, int x) {
    
    
        if (x == s.size() - 1) {
    
    
            res.push_back(s);
            return;
        }
        set<int> st;
        for (int i = x; i < s.size(); i++) {
    
    
            if (st.find(s[i]) != st.end()) continue;
            st.insert(s[i]);
            swap(s[i], s[x]);
            dfs(s, x + 1);
            swap(s[i], s[x]);
        }
    }
    vector<string> permutation(string s) {
    
    
        dfs(s, 0);
        return res;
    }
};

39. 剑指 Offer 39 数组中出现次数超过一半的数字

class Solution {
    
    
public:
    int majorityElement(vector<int>& nums) {
    
    
        //摩尔投票法
        int x = 0, votes = 0;
        for (int num : nums) {
    
    
            if (votes == 0) x = num;
            votes += num == x ? 1 : -1;
        }
        return x;
    }
};


class Solution {
    
    
public:
    int majorityElement(vector<int>& nums) {
    
    
        sort(nums.begin(), nums.end());
        return nums[nums.size()  / 2];
    }
};

40. 剑指 Offer 40 最小的k个数

class Solution {
    
    
public:
    void quicksort(vector<int>& v, int start, int end) {
    
    
        if (start >= end) {
    
    
            return;
        }
        int base = v[end];
        int left = start;
        int right = end - 1;

        while (left < right) {
    
    
            while(left < right && v[left] < base) {
    
    
                left++;
            }
            while (left < right && v[right] >= base) {
    
    
                right--;
            }
            std::swap(v[left], v[right]);
        }
        if (v[left] >= v[end]) {
    
    
            std::swap(v[left], v[end]);
        } else {
    
    
            left++;
        }
        if (start < left - 1) {
    
    
            quicksort(v, start, left - 1);
        }
        if (left + 1 <  end) {
    
    
            quicksort(v, left + 1, end);
        }
        return ;
    }
    vector<int> getLeastNumbers(vector<int>& arr, int k) {
    
    
        quicksort(arr, 0, arr.size() - 1);
        vector<int> res;
        res.assign(arr.begin(), arr.begin() + k);
        return res;
    }
};


猜你喜欢

转载自blog.csdn.net/weixin_44847326/article/details/125621473
今日推荐