剑指offer所有的题目总结(持续更新题解中...)

剑指offer所有的题目总结(c++:2刷)

文章目录

面试题3:数组中重复的数字

题目一:找出数组中重复的数字

class Solution {
   
public:
    int duplicateInArray(vector<int>& nums) {
   
        int n = nums.size();
        //超过数据范围,无效
        for(auto x : nums)
            if(x < 0 || x >= n)
                return -1;
        for(int i = 0; i < n; i++)
        {
   
            //如果当前坐标上的m和坐标不同,而且m坐标上的数也不等于m,则交换
            while(i != nums[i] && nums[i] != nums[nums[i]]) swap(nums[i], nums[nums[i]]);
            //如果当前坑与萝卜不匹配,且属于萝卜的坑已经有萝卜了则为重复萝卜
            if(nums[i] != i && nums[nums[i]] == nums[i])return nums[i];
        }
        return -1;
    }
};

题目二:不修改数组找出重复的数字

class Solution {
   
public:
    int duplicateInArray(vector<int>& nums) {
   
        int l = 1, r = nums.size() - 1;
        //利用抽屉原理,把长度分成两份,有一份一定会多出来
        while(l < r)
        {
   
            int mid = l + r >> 1;
            int s = 0;
            //统计区间[l, mid]中的数字
            for(auto x : nums) s += x >= l && x <= mid;
            if(s > mid - l + 1) r = mid;
            else l = mid + 1;
        }
        return r;
    }
};

面试题4:二维数组中的查找

class Solution {
   
public:
    bool searchArray(vector<vector<int>> array, int target) {
   
        //如果是空,则返回
        if(array.empty() || array[0].empty()) return false;
        //利用数组的特性,从右上角开始进行
        int i = 0, j = array[0].size() - 1;
        //每次可以排除一列或者一行
        while(i < array.size()  && j >= 0)
        {
   
            if(array[i][j] == target) return true;
            if(array[i][j] > target) j--;
            else i++;
        }
        return false;
    }
};

面试题5:替换空格

class Solution {
   
public:
    string replaceSpaces(string &str) {
   
        //首先遍历一遍得到新的字符串的长度,用双指针也是很棒的做法
        string newstr;
        for(auto x : str)
        {
   
            //如果是空格则加上字符
            if(x == ' ')newstr += "%20";
            //否则复制
            else newstr += x;
        }
        return newstr;
    }
};

面试题6:从尾到头打印链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
   
public:
    vector<int> printListReversingly(ListNode* head) {
   
        vector<int> res;
        while(head)
        {
   
            res.push_back(head->val);
            head = head->next;
        }
        //类似栈,利用栈的性质
        return vector<int>(res.rbegin(), res.rend());
    }
};

面试题7:重建二叉树

/**
 * 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:
    map<int, int> hash;
    vector<int> preorder, inorder;

    TreeNode* buildTree(vector<int>& _preorder, vector<int>& _inorder) {
   
        preorder = _preorder, inorder = _inorder;
        //记录根节点在中序中的位置
        for(int i = 0; i < inorder.size(); i++) hash[inorder[i]] = i;
        return dfs(0, preorder.size() - 1, 0, inorder.size() - 1);
    }

    TreeNode* dfs(int pl, int pr, int il, int ir)
    {
   
        if(pl > pr) return nullptr;
        auto root = new TreeNode(preorder[pl]);
        //找到位置
        int k = hash[root->val];
        //递归左边的树
        auto left = dfs(pl + 1, pl + k - il, il, k - 1);
        //递归右边的树
        auto right = dfs(pl + k - il + 1, pr, k + 1, ir);
        root->left = left;
        root->right = right;
        return root;
    }
};

面试题8:二叉树的下一个节点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode *father;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL), father(NULL) {}
 * };
 */
class Solution {
   
public:
    TreeNode* inorderSuccessor(TreeNode* p) {
   
        //分为两种情况
        if(p->right)
        {
   
            p = p->right;
            while(p->left) p = p->left;
            return p;
        }

        while(p->father && p == p->father->right) p = p->father;
        return p->father;
    }
};

面试题9:用两个栈实现队列

class MyQueue {
   
public:
    //利用两个栈
    /** Initialize your data structure here. */
    stack<int> stk, cache;
    MyQueue() {
   

    }

    /** Push element x to the back of queue. */
    void push(int x) {
   
        stk.push(x);
    }

    void copy(stack<int> &a, stack<int> &b)
    {
   
        while(a.size())
        {
   
            b.push(a.top());
            a.pop();
        }
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
   
        copy(stk, cache);
        int res = cache.top();
        cache.pop();
        copy(cache, stk);
        return res;
    }

    /** Get the front element. */
    int peek() {
   
        copy(stk, cache);
        int res = cache.top();
        copy(cache, stk);
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
   
        return stk.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */

面试题10:斐波那契数列

class Solution {
   
public:
    int Fibonacci(int n) {
   
        int a = 0, b = 1;
        while(n--)
        {
   
            int c = a + b;
            a = b, b = c;
        }
        return a;
    }
};

面试题11:旋转数组的最小数字

class Solution {
   
public:
    int findMin(vector<int>& nums) {
   
        //二分
        int n = nums.size() - 1;
        if(n < 0) return -1;
        //去除重复数字
        while(n > 0 && nums[n] == nums[0])n--;
        if(nums[n] > nums[0]) return nums[0];
        int l = 0, r = n;
        while(l < r)
        {
   
            int mid = l + r >> 1;
            if(nums[mid] < nums[0]) r = mid;
            else l = mid + 1;
        }
        return nums[r];
    }
};

面试题12:矩阵中的路径

class Solution {
   
public:
    bool hasPath(vector<vector<char>>& matrix, string str) {
   
        for (int i = 0; i < matrix.size(); i ++ )
            for (int j = 0; j < matrix[i].size(); j ++ )
                if (dfs(matrix, str, 0, i, j))
                    return true;
        return false;
    }

    bool dfs(vector<vector<char>> &matrix, string &str, int u, int x, int y) {
   
        if (matrix[x][y] != str[u]) return false;
        if (u == str.size() - 1) return true;
        int dx[4] = {
   -1, 0, 1, 0}, dy[4] = {
   0, 1, 0, -1};
        char t = matrix[x][y];
        matrix[x][y] = '*';
        for (int i = 0; i < 4; i ++ ) {
   
            int a = x + dx[i], b = y + dy[i];
            if (a >= 0 && a < matrix.size() && b >= 0 && b < matrix[a].size()) {
   
                if (dfs(matrix, str, u + 1, a, b)) return true;
            }
        }
        matrix[x][y] = t;
        return false;
    }
};

面试题13:机器人的运动范围

class Solution {
   
public:
    int get_single_sum(int x)
    {
   
        int s = 0;
        while(x) s += x % 10, x /= 10;
        return s;
    }

    int get_sum(pair<int, int> p)
    {
   
        return get_single_sum(p.first) + get_single_sum(p.second);
    }

    int movingCount(int threshold, int rows, int cols)
    {
   
        int res = 0;

        //判断边界条件
        if(!rows || !cols) return 0;

        vector<vector<bool>> st(rows, vector<bool>(cols));
        queue<pair<int, int>> q;

        //首先放入起点
        q.push({
   0, 0});

        //四个方向
        int dx[4] = {
   -1, 0, 1, 0};
        int dy[4] = {
    0, 1, 0, -1};

        while(q.size())
        {
   
            auto t = q.front();
            q.pop();

            //判断是否超出条件
            if(get_sum(t) > threshold || st[t.first][t.second]) continue;
            //统计结果
            res++;
            st[t.first][t.second] = true;

            //没有超过就加入边界
            for(int i = 0; i < 4; i++)
            {
   
                int x = t.first + dx[i];
                int y = t.second + dy[i];
                if(x >= 0 && x < rows && y >= 0 && y < cols)
                {
   
                    q.push({
   x, y});
                }
            }

        }
        return res;
    }
};

面试题14:剪绳子

class Solution {
   
public:
    int maxProductAfterCutting(int n) {
   
        if(n <= 3) return 1*(n - 1);
        //尽可能的取3
        
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值