剑指Offer刷题笔记--题目03-10

目录

1--数组中重复的数字(03)

2--二维数组中的查找(04)

3--替换空格(05)

4--从尾到头打印链表(06)

5--重建二叉树(07)

6--用两个栈实现队列(09)

7--斐波拉契数列(10)

8--青蛙跳台阶问题(10)


1--数组中重复的数字(03)

解决方法1:

        基于哈希表,将数组中的元素视为 Key,其对应的 Value 设为 True;遍历每一个元素,查询元素 Key 对应的 Value,若为 True 表示之前已经出现了它的重复元素;否则将元素 Key 对应的 Value 设为 True,保存在哈希表中;

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
 
// 基于哈希表
class Solution {
public:
    int findRepeatNumber(std::vector<int>& nums) {
        std::unordered_map<int, bool> map;
        for(int num : nums) {
            if(map[num]) return num;
            map[num] = true;
        }
        return -1;
    }
};
 
int main(int argc, char *argv[]){
    std::vector<int> v1 = {2, 3, 1, 0, 2, 5, 3};
    Solution s1;
    int num = s1.findRepeatNumber(v1);
    std::cout << "num: " << num << std::endl;
    return 0; 
}

解决方法2:

        利用原地交换,将索引位置 i 与位置上的值 nums[i] 匹配上;

题解的一个易懂解释:

        这个原地交换法就相当于分配工作,每个索引代表一个工作岗位,每个岗位必须专业对口,既0索引必须0元素才能上岗。而我们的目的就是找出溢出的人才,既0索引岗位有多个0元素竞争。

        我们先从0索引岗位开始遍历,首先我们看0索引是不是已经专业对口了,如果已经专业对口既nums[0]=0,那我们就跳过0岗位看1岗位。如果0索引没有专业对口,那么我们看现在0索引上的人才调整到他对应的岗位上,比如num[0]=2,那我们就把2这个元素挪到他对应的岗位上既num[2],这个时候有两种情况:1、num[2]岗位上已经有专业对口的人才了,既num[2]=2,这就说明刚刚那个在num[0]上的2是溢出的人才,我们直接将其返回即可。2、num[2]上的不是专业对口的人才,那我们将num[0]上的元素和num[2]上的元素交换,这样num[2]就找到专业对口的人才了。之后重复这个过程直到帮num[0]找到专业对口的人才,然后以此类推帮num[1]找人才、帮num[2]找人才,直到找到溢出的人才。

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>

// 核心思路是使索引位置i 与 位置i上的值nums[i]相等
class Solution {
public:
    int findRepeatNumber(std::vector<int>& nums) {
        int i = 0;
        while(i < nums.size()){
            if(nums[i] == i){ // 当前索引的位置i 与 位置的值nums[i] 相等
                i++;
                continue; // 无须进行后面的交换操作
            }
            if(nums[nums[i]] == nums[i]) return nums[i];
            else std::swap(nums[i], nums[nums[i]]); // 交换
        }
        return -1;
    }
};

int main(int argc, char *argv[]){
    std::vector<int> v1 = {2, 3, 1, 0, 2, 5, 3};
    Solution s1;
    int num = s1.findRepeatNumber(v1);
    std::cout << "num: " << num << std::endl;
    return 0; 
}

2--二维数组中的查找(04)

暴力法求解:        

        遍历每一个一维数组,通过STL标准库 find() 函数寻找目标整数;

#include <iostream>
#include <vector>
#include <algorithm>

class Solution {
public:
    bool findNumberIn2DArray(std::vector<std::vector<int>>& matrix, int target) {
        for(auto it1 = matrix.begin(); it1 != matrix.end(); it1++){
            auto loc = find((*it1).begin(), (*it1).end(), target);
            if(loc != (*it1).end())
                return true;
        }
        return false;
    }
};

int main(int argc, char *argv[]){
    std::vector<int> m1 = {1, 4, 7, 11, 15};
    std::vector<int> m2 = {2, 5, 8, 12, 19};
    std::vector<int> m3 = {3, 6, 9, 16, 22};
    std::vector<int> m4 = {10, 13, 14, 17, 24};
    std::vector<int> m5 = {18, 21, 23, 26, 30};
    std::vector<std::vector<int>> matrix = {m1, m2, m3, m4, m5};
    Solution s1;
    bool stat1 = s1.findNumberIn2DArray(matrix, 5);
    bool stat2 = s1.findNumberIn2DArray(matrix, 20);
    std::cout << "stat1: " << stat1 << std::endl;
    std::cout << "stat2: " << stat2 << std::endl;
    return 0; 
}

搜索树解法:

        将矩阵逆时针旋转 45°,将其转化为图的形式,其搜索等价于二叉搜索树,具体见题解;

#include <iostream>
#include <vector>
#include <algorithm>

class Solution {
public:
    bool findNumberIn2DArray(std::vector<std::vector<int>>& matrix, int target) {
        int i = matrix.size() - 1, j = 0;
        while(i >= 0 && j < matrix[0].size())
        {
            if(matrix[i][j] > target) i--;
            else if(matrix[i][j] < target) j++;
            else return true;
        }
        return false;
    }
};

int main(int argc, char *argv[]){
    std::vector<int> m1 = {1, 4, 7, 11, 15};
    std::vector<int> m2 = {2, 5, 8, 12, 19};
    std::vector<int> m3 = {3, 6, 9, 16, 22};
    std::vector<int> m4 = {10, 13, 14, 17, 24};
    std::vector<int> m5 = {18, 21, 23, 26, 30};
    std::vector<std::vector<int>> matrix = {m1, m2, m3, m4, m5};
    Solution s1;
    bool stat1 = s1.findNumberIn2DArray(matrix, 5);
    bool stat2 = s1.findNumberIn2DArray(matrix, 20);
    std::cout << "stat1: " << stat1 << std::endl;
    std::cout << "stat2: " << stat2 << std::endl;
    return 0; 
}

3--替换空格(05)

原地修改:

        不新建字符串,遍历输入的字符串,判断字符是否等于空格,是空格则删除,并插入“%20”,遍历后移3位,最后返回原字符串;

#include <iostream>
#include <string>

class Solution {
public:
    std::string replaceSpace(std::string s) {
        for (int i = 0; i < s.size(); i++){
            if (s[i] ==  ' '){
                s.erase(i, 1);
                s.insert(i, "%20");
                i = i + 2;
            }
        }
        return s;
    }
};

int main(int argc, char *argv[]){
    std::string s1 = "We are happy.";
    Solution Func;
    std::string s2 = Func.replaceSpace(s1);
    std::cout << "s2: " << s2 << std::endl;
}

新建字符串:

        遍历输入的字符串,判断当前字符是否等于空格,是空格则新字符串添加“%20”,否则添加当前字符,最后返回新字符串;

#include <iostream>
#include <string>

class Solution {
public:
    std::string replaceSpace(std::string s) {
        std::string s1;
        for(auto item : s){
            if (item == ' ') s1 = s1 + "%20";
            else s1 = s1 + item;
        }
        return s1;
    }
};

int main(int argc, char *argv[]){
    std::string s1 = "We are happy.";
    Solution Func;
    std::string s2 = Func.replaceSpace(s1);
    std::cout << "s2: " << s2 << std::endl;
}

4--从尾到头打印链表(06)

        借助STL中 vector 的 insert() 函数,遍历链表时每次都在开头插入新的元素:

#include <iostream>
#include <vector>

struct ListNode {
    ListNode(){}; // 构造函数

    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    std::vector<int> reversePrint(ListNode* head) {
        std::vector<int> v1;
        ListNode* pos = head;
        while(pos != NULL){
            v1.insert(v1.begin(), pos->val);
            pos = pos -> next; 
        } 
        return v1;
    }
};

int main(int argc, char *argv[]){
    ListNode *head = new ListNode(1);
    ListNode *node1 = new ListNode(3);
    ListNode *node2 = new ListNode(2);
    head->next = node1;
    node1->next = node2;
    Solution s1; 
    std::vector<int> v1 = s1.reversePrint(head);
    for(auto item : v1){
        std::cout << "item: " << item << std::endl;
    }
}

        分析题目,先遍历出现的元素后返回,即先进后出,符合栈的规律,可借助递归实现,递归终止的条件是当前结点的指针为空;

#include <iostream>
#include <vector>

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    std::vector<int> reversePrint(ListNode* head) {
        if(!head)
            return {};
        std::vector<int> a = reversePrint(head->next);
        a.push_back(head->val);
        return a;
    }
};

int main(int argc, char *argv[]){
    ListNode *head = new ListNode(1);
    ListNode *node1 = new ListNode(3);
    ListNode *node2 = new ListNode(2);
    head->next = node1;
    node1->next = node2;
    Solution s1; 
    std::vector<int> v1 = s1.reversePrint(head);
    for(auto item : v1){
        std::cout << "item: " << item << std::endl;
    }
}

5--重建二叉树(07)

主要思路:

        前序遍历第一个肯定是根节点,中序遍历根节点左边是左子树,右边是右子树;

        因此,在中序遍历定位根节点的位置后,可以递归处理左子树和右子树;

        左子树和右子树的起始和结束位置可以根据左子树的大小确定;

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        for(int i = 0; i < n; i++){
            m1[inorder[i]] = i; 
        }
        TreeNode* Tree = mybuildTree(preorder, inorder, 0, n-1, 0, n-1);
        return Tree;
    }

    TreeNode* mybuildTree(vector<int>& preorder, vector<int>& inorder, int p_start, int p_end, 
                                            int i_start, int i_end){
        if( p_start > p_end){
            return nullptr;
        }
        TreeNode *Root = new TreeNode(preorder[p_start]);
        int Root_idx = m1[preorder[p_start]]; 
        int left_tree_size = Root_idx - i_start;
        Root->left = mybuildTree(preorder, inorder, p_start+1, p_start+left_tree_size, 
                                            i_start, Root_idx-1);
        Root->right = mybuildTree(preorder, inorder, p_start+1+left_tree_size, p_end, Root_idx+1, i_end);
        return Root;
    }
    std::map<int, int> m1;
};

6--用两个栈实现队列(09)

 建立两个栈,一个作为输入栈,一个作为输出栈;输出队列时,直接返回输出栈的栈顶元素;当输出栈为空时,如果输入栈不会空,就把输入栈的元素移动到输出栈中;如果输入栈也为空则表示队列为空,返回-1;

class CQueue {
public:
    CQueue() {

    }
    
    void appendTail(int value) {
        in_stack.push(value);
    }
    
    int deleteHead() {
        if (out_stack.size() != 0){
            elem = out_stack.top();
            out_stack.pop();
            return elem;
        } 
        else{
            if(in_stack.size() == 0){
                return -1;
            }
            else{
                int instack_size = in_stack.size();
                for(int i = 0; i < instack_size; i++){
                    elem = in_stack.top();
                    out_stack.push(elem);
                    in_stack.pop();
                }
                elem = out_stack.top();
                out_stack.pop();
                return elem;
            }
        }
    }
    std::stack<int> in_stack;
    std::stack<int> out_stack;
    int elem;
};

7--斐波拉契数列(10)

        经典动态规划题目,使用递归会导致内存消耗大、运行时间长等问题,利用递推的方式实现求解:从 F(2) = F(1) + F(0) 开始递推,利用变量记录当前的F(N-1)和F(N-2);

class Solution {
public:
    int fib(int n) {
        if (n < 2){
            return n;
        }
        int f_1 = 0, f_2 = 0, sum = 1;
        for(int i = 2; i <= n; i++){
            f_2 = f_1;
            f_1 = sum;
            sum = (m1 + m2) % 1000000007;
        }
        return sum;
    }
};

8--青蛙跳台阶问题(10)

设 n 阶台阶有 f(n) 种跳法,假设最后一步只跳一阶,则剩下的 n-1 个台阶有 f(n-1) 种跳法;假设最后一步跳两阶,则剩下的 n-2 个台阶有 f(n-2) 种跳法;即 f(n) = f(n-1) + f(n-2);

边界条件:f(0) = 1;f(1) = 1;f(2) = 2;

class Solution {
public:
    int numWays(int n) {
        int f1 = 1, f2 = 0, sum = 1;
        for(int i = 0; i < n; i++){
            sum = (f1 + f2) % 1000000007;
            f2 = f1;
            f1 = sum;           
        }
        return sum; 
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43863869/article/details/130532717
今日推荐