剑指offer(1题-11题)

找出数组中重复的数字

题意

image-20200806173049290

思路

桶排序

代码

class Solution {
public:
    int duplicateInArray(vector<int>& nums) {
        int n=nums.size();
        for(int i=0;i<n;i++)
            if(nums[i]<0 || nums[i]>=n)
                return -1;
        int st[n];
        memset(st,0,sizeof st);
        for(int i=0;i<n;i++)
            if(st[nums[i]])
                return nums[i];
            else st[nums[i]]++;
        return -1;
    }
};

不修改数组找出重复的数字(只能用O(1)空间

题意

image-20200806173443848

思路

​ 数字范围是1-n公n个数,但是nums有n+1个数。说明n个坑,填n+1个数。抽屉原理,必有一个坑,有俩个数, 使用二分,找一边数的个数大与坑的数,check进去。

​ 总思路是,将坑的序号进行二分,对一边所有坑统计数字总和进行check。若这一边坑里面的数>坑的个数,那么这一边true。

代码

class Solution {
public:
    int duplicateInArray(vector<int>& nums) {
        int l=1,r=nums.size()-1;
        
        while(l<r)
        {
            int mid=r+l>>1;
            int s=0;
            for(auto x:nums) 
                if(x>=l && x<=mid)
                    s++;
            if(s>mid-l+1) r=mid;
            else l=mid+1;
        }
        return r;
    }
};

二维数组的查找

题意

image-20200806175611879

思路

​ 具有一种单调性:

		* 数组中(i,j)的位置,i左边都比它小,j下边都比它大
  • 从右上角找
    • 要找的数比右上角小,那么j–
    • 要找的数比右上角大,那么i++
  • 直到找到数字
  • 这个过程用while循环

代码

class Solution {
public:
    bool searchArray(vector<vector<int>> array, int target) {
        if(array.empty()) return false;
    
        int i=0,j=array[0].size()-1;
        //cout<<i<<' '<<j<<endl;
        while(i<array.size() && j>=0)
        {
            if(array[i][j] == target) return true;
            if(array[i][j] >target) j--;
            else i++;
        }
        return false;
    }
};

替换空格

题意

水题

代码

class Solution {
public:
    string replaceSpaces(string &str) {
        string s;
        for(auto x:str)
            if(x==' ') s=s+"%20";
            else s=s+x;
        return s;
    }
};

从尾到头打印链表

题意

​ 逆序输出链表的值

代码

/**
 * 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;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

重建二叉树

题意

image-20200806180557998

思路

​ 前序+中序确定二叉树

  • 前序遍历确定根节点
  • 找到根节点,在中序遍历中确定左子树大小,右子树大小
  • 快速找到前序中根节点在中序中位置:hash表
  • 递归建立某一区间的二叉树
    • 变量
      • 前序数列,前序在这一区间的范围
      • 中序数列,中序在这一区间的范围
  • 总之:前序遍历确定根,dfs中序建立树, 递归过程中用一个变量代表左子树长度。

代码

/**
 * 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:

    unordered_map<int,int> pos;

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        for (int i = 0; i < n; i ++ )
            pos[inorder[i]] = i;
        return dfs(preorder, inorder, 0, n - 1, 0, n - 1);
    }

    TreeNode* dfs(vector<int>&pre, vector<int>&in, int pl, int pr, int il, int ir)
    {
        if (pl > pr) return NULL;
        int k = pos[pre[pl]] - il;
        TreeNode* root = new TreeNode(pre[pl]);
        root->left = dfs(pre, in, pl + 1, pl + k, il, il + k - 1);
        root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir);
        return root;
    }
};

二叉树的下一个节点(树的后继)

题意

image-20200806211830868

思路

  • 这颗树有右子树,
    • 后继就是右子树的左子树的左子树的左子树
  • 没有右子树
    • 一直往上找,找到节点是父节点的左儿子
    • image-20200806212255005
    • 否则 没有后继

代码

/**
 * 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->father->right == p)
            p=p->father;
         if(p->father) return p->father;
        return NULL;
    }
};

用俩个栈实现队列

题意


思路

​ 每次操作很暴力的模拟

代码

class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int>st,temp;
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        st.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        while(st.size())
        {
            temp.push(st.top());
            st.pop();
        }
        int a=temp.top();
         temp.pop();
        while(temp.size())
        {
            st.push(temp.top());
            temp.pop();
        }
        return a;
    }
    
    /** Get the front element. */
    int peek() {
        while(st.size())
        {
            temp.push(st.top());
            st.pop();
        }
        int a=temp.top();
       
        while(temp.size())
        {
            st.push(temp.top());
            temp.pop();
        }
        return a;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return st.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();
 */

旋转数组的最小数字

题意

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。

输入一个升序的数组的一个旋转,输出旋转数组的最小元素。

例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。

数组可能包含重复项。

注意:数组内所含元素非负,若数组大小为0,请返回-1。

样例
输入:nums=[2,2,2,0,1]

输出:0

思路:

​ 是具有单调性质的,可以二分。特判一下,序列直接单调上升,直接输出答案。需要注意,包含重复项。

image-20200806213206688

​ 用while循环去掉最后那部分直线,剩下就是二分找最小值,

代码

class Solution {
public:
    int findMin(vector<int>& nums) {
        if(nums.size()==0) return -1;
        int n=nums.size()-1;
        while(n && nums[n]==nums[n-1]) 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];
    }
};

矩阵中的路径:(dfs找路径:先st,后循环)

代码

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[0].size();j++)
                if(dfs(matrix,str,i,j,0))   return true;
        return false;
    }
    int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
    bool dfs(vector<vector<char>>& g, string &s,int a,int b,int u)
    {
        if(g[a][b]!=s[u]) return false;
        if(u>=s.size()-1)
            return true;
        
        char t=g[a][b];
        g[a][b]='*';
        for(int i=0;i<4;i++)
        {
            int nx=a+dx[i];
            int ny=b+dy[i];
            if(nx<0 || nx>g.size()-1 || ny<0 || ny>g[0].size()-1) continue;
           
            if(dfs(g,s,nx,ny,u+1)) return true;
         
        }
        g[a][b]=t;
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值