当前位置:   article > 正文

剑指offer牛客网刷题_给定两个只包含数字的数组a, b, 调整数组a里面数字的顺序,使得尽可能多的a[i] >

给定两个只包含数字的数组a, b, 调整数组a里面数字的顺序,使得尽可能多的a[i] >

主要参考剑指offer书籍和博主https://blog.csdn.net/Rrui7739/article/details/96020389在此表示感谢
黑色的表示简单,粉色的表示中等,红色的表示困难

1 二维数组的查找

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {     
        if(array.size()==0 && array[0].size()==0)
            return false;     
        for(int i=0;i<array.size();i++){
            int left = 0, right = array[0].size()-1, up = 0, down = array.size()-1;
             while(left<=right)
            {
                int mid =  (right + left)/2;
                if(array[i][mid]<target)
                    left = mid + 1;
                else if(array[i][mid]>target)
                    right = mid-1;
                else return true;
            }
        }     
        return false;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

注:一次循环加二分查找

2 替换空格

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

class Solution {
public:
	void replaceSpace(char *str,int length) {
        if(str==nullptr||length<1)
            return;
        char *p1=str;
        int strlength=0,nulength=0;
        while(*p1!='\0'){
            if(*p1==' ')
                nulength++;      
                strlength++;
            p1++;
        }
        int totallen=strlength+nulength*2;
        while(totallen!=strlength){
            if(str[strlength]==' '){
                str[totallen--]='0';
                str[totallen--]='2';
                str[totallen--]='%';
            }
            else
                str[totallen--]=str[strlength];
            strlength--;            
        }
	}
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

注:两个指针

3 从尾到头打印链表

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        if(head==nullptr)
            return {};
        vector<int> output;
        stack<ListNode*> s;
        while(head){
            s.push(head);
            head=head->next;
        }
        while(!s.empty()){
            output.push_back(s.top()->val);
            s.pop();
        }
        return output;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

注:利用栈思想

4 重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        if(pre.size()==0||pre.size()!=vin.size())
            return nullptr;
        TreeNode* p1= reConstructBinaryTree1(pre,vin,0,pre.size()-1,0,vin.size()-1);
        return p1;
    }
    TreeNode* reConstructBinaryTree1(vector<int> &pre,vector<int> &vin,int left1,int right1,int left2,int right2){
        if(left1>right1)//没有等于,等于的话返回相等的值可以不写
            return nullptr;
        TreeNode*p=new TreeNode(pre[left1]);
        int x=0;
        for(int i=left2;i<=right2;i++){
            if(pre[left1]==vin[i]){
                x=i;
                break;
            }
        }
        p->left=reConstructBinaryTree1(pre,vin,left1+1,x-left2+left1,left2,x-1);
        p->right=reConstructBinaryTree1(pre,vin,x-left2+left1+1,right1,x+1,right2);
        return p;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

注:因为是树的结构,一般都是用递归来实现。
用数学归纳法的思想就是,假设最后一步,就是root的左右子树都已经重建好了,那么我只要考虑将root的左右子树安上去即可。
根据前序遍历的性质,第一个元素必然就是root,那么下面的工作就是如何确定root的左右子树的范围。
根据中序遍历的性质,root元素前面都是root的左子树,后面都是root的右子树。那么我们只要找到中序遍历中root的位置,就可以确定好左右子树的范围。
正如上面所说,只需要将确定的左右子树安到root上即可。递归要注意出口,假设最后只有一个元素了,那么就要返回。

5 用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
        }
        int a=stack2.top();
        stack2.pop();
        while(!stack2.empty()){
            stack1.push(stack2.top());
            stack2.pop();
        }
        return a;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

注: 两个栈来回倒

旋转数组的最小数字

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

class Solution {
public:
    int minNumberInRotateArray(vector<int> rotateArray) {
        if(rotateArray.size()==0)
            return 0;
        int left=0,right=rotateArray.size()-1;
        while(left<right){
            int mid=(left+right)/2;
            if(rotateArray[mid]>rotateArray[right])
                left=mid+1;
            else if(rotateArray[mid]<rotateArray[right])
                right=mid;//mid不能-1,没想明白
            else ++left;
        }
        return rotateArray[left];//这里直接输出left
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注:利用旋转数组的性质与二分法,如果left指针小于mid指针就说明左面是连续数组,right指针大于mid就说明右面是连续数组,如果都相等则left自加即可。

斐波那契数列

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。

class Solution {
public:
    int Fibonacci(int n) {
        if(n<0)
            return -1;
        vector<int> output(n+1,0);
        output[1]=1;
        int i=2;
        while(i<=n){
            output[i]=output[i-2]+output[i-1];
            i++;
        }
        return output[n];

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

注:简单的动态规划题,斐波那契数列是f(0)=0,f(1)=1,f(n)=f(n-1)+f(n-2),可以从i=0到i=n从下至上的考虑。这样简单很多。

青蛙跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

class Solution {
public:
    int jumpFloor(int number) {
        if(number<=0)
            return 0;
        vector<int> cache(number+1,1);
        cache[2]=2;
        for(int i=3;i<number+1;i++){
            cache[i]=cache[i-1]+cache[i-2];
        }
        return cache[number];
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

注:同上

变态跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

class Solution {
public:
    int jumpFloorII(int number) {
        if(number<=0)
            return 0;
        vector<int> cache(number+1,1);
        cache[2]=2;
        for(int i=3;i<number+1;i++){
            int num=0,j=i-1;
            while(j>0){
                num+=cache[j--];
            }
            cache[i]=num+1;
        }
        return cache[number];

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

注: 同上

矩形覆盖

我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

class Solution {
public:
    int rectCover(int number) {
        if(number<=0)
            return 0;
        vector<int> cache(number+1,1);
        cache[2]=2;
        //cache[3]=3;
        for(int i=3;i<number+1;i++){
            cache[i]=cache[i-1]+cache[i-2];
        }
        return cache[number];

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注:矩阵只有竖着和横着两种状态,所以f(n)=f(n-1)+f(n-2);

二进制中1的个数

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示

class Solution {
public:
     int  NumberOf1(int n) {
         int count=0;
         while(n){
             count++;
             n=n&(n-1);
         }
         return count;
     }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

注:想不出来就用常规解法做左移运算,因为有负数不能右移

数值的整数n次方

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0

class Solution {
public:
    double Power(double base, int exponent) {
        if(exponent==0)
            return 1;
        int flag=1;
        if(exponent<0){
            exponent=-exponent;
            flag=-1;
        }
        double cache=Power1(base,exponent);
        if(flag==-1)
            cache=1/cache;
        return cache;
    
    }
    double Power1(double base, int exponent){
        if(exponent==1)
            return base;
        double cache=Power1(base,exponent>>1);
        if(exponent%2==1)
            return cache*cache*base;
        else return cache*cache;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

调整数组顺寻使奇数位于偶数前面

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变

class Solution {
public:
    void reOrderArray(vector<int> &array) {
        vector<int> cache1;
        vector<int> cache2;
        for(int i=0;i<array.size();i++){
            if(array[i]%2==1)
                cache1.push_back(array[i]);
            else
                cache2.push_back(array[i]);
        }
        for(int i=0;i<cache2.size();i++)
            cache1.push_back(cache2[i]);
        array=cache1;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

注:如果不要求相对顺序不变则可以使用双指针,但是题目要求相对顺序不变,定义一个额外数组,遍历两遍原数组即可。

链表中倒数第k个结点

输入一个链表,输出该链表中倒数第k个结点。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if(pListHead==nullptr) 
            return nullptr;
        ListNode* p1=pListHead;
        ListNode* p2=pListHead;
        while(k){
            if(p2==nullptr)
                return nullptr;
            p2=p2->next;
            k--;
        }
        while(p2){
            p2=p2->next;
            p1=p1->next;
        }
        return p1;
    
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

注:使用快慢指针,快的先比慢的走k步,然后再一起一步一步的走,这里需要注意k有可能是非法值,有可能小于等于0,或者直接就大于整个链表长度,这时需要返回nullptr指针。

反转链表

输入一个链表,反转链表后,输出新链表的表头。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==nullptr||pHead->next==nullptr)
            return pHead;
        ListNode* pnext=pHead;
        ListNode* current=nullptr;
        while(pnext){
            ListNode* p=pnext->next;
            pnext->next=current;
            current=pnext;
            pnext=p;
            
        }
        return current;//返回的不是pnext

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

注:先复制下一个节点后再断开连接,每次还要记录当前节点

合并两个有序的链表

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1==nullptr)
            return pHead2;
        if(pHead2==nullptr)
            return pHead1;
        ListNode* p=new ListNode(0);
        ListNode* p1=p;//记录头节点
        while(pHead1&&pHead2){
            if(pHead1->val<pHead2->val){
                p->next=pHead1;
                pHead1=pHead1->next;
                p=p->next;//不要忘记
            }
            else{
                 p->next=pHead2;
                pHead2=pHead2->next;
                p=p->next;//不要忘记
            }
            
        }
        if(pHead1){
            p->next=pHead1;
        }
        if(pHead2){
            p->next=pHead2;
        }
        return p1->next;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

注:两个指针比较大小,不要忘记记录头节点

树的子结构

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if(pRoot1==nullptr||pRoot2==nullptr)
            return false;
        //return HasSubtree1(pRoot1,pRoot2);这里忘记下面的搜索了
        if(HasSubtree1(pRoot1,pRoot2))
            return true;
        else return HasSubtree(pRoot1->left,pRoot2)||HasSubtree(pRoot1->right,pRoot2);

    }
    bool HasSubtree1(TreeNode* pRoot1, TreeNode* pRoot2){
        if(pRoot2==nullptr)
            return true;
        if(pRoot1==nullptr)
            return false;
        if(pRoot1->val==pRoot2->val)
            return HasSubtree1(pRoot1->left,pRoot2->left)&&HasSubtree1(pRoot1->right,pRoot2->right);
        else return false;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

注:递归判断各子树有没有这个结构就好了。

二叉树的镜像

操作给定的二叉树,将其变换为源二叉树的镜像

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot==nullptr)
            return;
        TreeNode *p=pRoot->left;
        pRoot->left=pRoot->right;
        pRoot->right=p;
        Mirror(pRoot->left);
        Mirror(pRoot->right);

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

注:递归交换左右子树就好了。

顺序打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        if(matrix.size()==0||matrix[0].size()==0)
            return {};
        vector<int> output;

        int left=0,up=0,right=matrix[0].size()-1,down=matrix.size()-1;
        while(left<=right&&up<=down){
            int left_c=left,right_c=right,up_c=up,down_c=down;
            while(left_c<=right){
                output.push_back(matrix[up][left_c++]);
            }
            up++;
            up_c++;
            while(up_c<=down){
                output.push_back(matrix[up_c++][right]);
            }
            right--;
            right_c--;
            while(left<=right_c&&up<=down){
                output.push_back(matrix[down][right_c--]);
            }
            down--;
            down_c--;
            while(up<=down_c&&left<=right){
                output.push_back(matrix[down_c--][left]);
            }
            left++;
        }
        return output;

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

注:主要注意一下从右至左以及从下至上打印的边界条件就好了。

包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。

class Solution {
public:
    void push(int value) {
        if(!s1.empty())
            s2.push(::min(value,s1.top()));//这要引用全局函数
        else
            s2.push(value);
        s1.push(value);
    }
    void pop() {
        if(s1.empty())
            return;
        s1.pop();
        s2.pop();
    }
    int top() {
        if(s1.empty())
            return 0;
        return s1.top();
    }
    int min() {
        if(s1.empty())
            return 0;
        return s2.top();
    }
    private:
    stack<int> s1;
    stack<int> s2;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

注:需要额外定义一个最小栈,每次压入弹出栈的时候都需要对最小栈进行操作以取得当前最小值。

栈的压入,弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        stack<int> s1;
        int i=0,j=0;
        while(i<pushV.size()){
            s1.push(pushV[i]);
                while(!s1.empty()&&s1.top()==popV[j]){
                    s1.pop();
                    j++;
                }
                i++;
            }
                
        return s1.empty();
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注:使用一个栈来模拟压入弹出即可。

从上到下打印二叉树

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        if(root==nullptr)
            return {};
        queue<TreeNode*> q;
        vector<int> output;
        q.push(root);
        while(!q.empty()){
            TreeNode* p=q.front();
            if(p->left)
                q.push(p->left);
            if(p->right)
                q.push(p->right);
            output.push_back(p->val);
            q.pop();
        }
        return output;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

注:使用队列进行层序遍历即可。

二叉树的后续遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        if (sequence.size() == 0)
            return false;
        int left = 0, right = sequence.size() - 1;
        return VerifySquenceOfBST1(sequence, left, right);

    }
    bool VerifySquenceOfBST1(vector<int>& sequence, int left,int right) {
        if (left >= right)
            return true;
        int mid;
        for(int i=left;i < right;i++) {
            if (sequence[i] > sequence[right]) {
                mid=i;
                break;
            }
        }
        for (int i=mid;i < right;i++) {
            if (sequence[i] < sequence[right])
                return false;
        }
        return VerifySquenceOfBST1(sequence,left,mid-1) && VerifySquenceOfBST1(sequence,mid,right-1);
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

注:根据二叉搜索树的性质,从后往前找根节点,找到根节点后找左右子树,分别验证左右子树是不是二叉搜索树(即左子树都比根节点小,右子树都比根节点大)即可。

二叉树中和为某一值的路径

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root==nullptr)
            return {};
        FindPath1(root,expectNumber);
        sort(output.begin(),output.end(),setting);
        return output;

    }
    void FindPath1(TreeNode* root,int expectNumber){
        if(root==nullptr)
            return;
        cache.push_back(root->val);
        if(!root->left&&!root->right&&root->val==expectNumber){
            output.push_back(cache);
            //return;
        }
        else{
        if(root->left)
            FindPath1(root->left,expectNumber-root->val);
        if(root->right)
            FindPath1(root->right,expectNumber-root->val);
        }
            cache.pop_back();
    }
    static bool setting(vector<int> a,vector<int> b){
        return a.size()>b.size();
    }
    private:
    vector<vector<int> > output;
    vector<int> cache;
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

注:挨个路径去验证就好了,验证完还需要对数组长度进行排序才能输出。

复杂链表的复制

/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        if(pHead==nullptr)
            return nullptr;
        RandomListNode* currNode=pHead;
        while(currNode){
            RandomListNode* cache=new RandomListNode(currNode->label);
            cache->next=currNode->next;
            currNode->next=cache;
            currNode=cache->next;
        }
        currNode=pHead;
        while(currNode){
            RandomListNode* currNodenext=currNode->next;
            if(currNode->random)
                currNodenext->random=currNode->random->next;
            currNode=currNodenext->next;
        }
        currNode=pHead;
        RandomListNode* cache1=currNode->next;
        RandomListNode* cache2;
        while(currNode->next){//这里循环断开要注意
            cache2=currNode->next;
            currNode->next=cache2->next;
            currNode=cache2;
        }
        return cache1;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

注:本题分三步走,第一步是复制链表,复制每一个结点为它的下一结点,例如ABCD就复制为AABBCCDD,第二步是复制random结点,第三步是断开连接(这里连接要全部断开,否则要报错)。

二叉搜索树与双向链表

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    TreeNode* Convert(TreeNode* pRootOfTree)
    {
        if(pRootOfTree==nullptr)
            return nullptr;
        TreeNode* pre=nullptr;
        Convert1(pRootOfTree,pre);
        while(pRootOfTree->left){
            pRootOfTree=pRootOfTree->left;
        }
        return pRootOfTree;
    }
    void Convert1(TreeNode* pRootOfTree,TreeNode* &pre){
        if(pRootOfTree==nullptr)
            return;
        Convert1(pRootOfTree->left,pre);
        pRootOfTree->left=pre;
        if(pre)
            pre->right=pRootOfTree;
        pre=pRootOfTree;//记录上一个节点
        Convert1(pRootOfTree->right,pre);
        
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

注:中序遍历即可。只需要记录一个pre指针即可。

字符串的排列

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

class Solution {
public:
    vector<string> Permutation(string str) {
        if(str.size()==0)
            return {};
        vector<string> output;
        int k=0;
        Permutation2(output,str,k);
        return output;
    }
    void Permutation2(vector<string> &output,string str,int k){
        if(k==str.size()){
            if(find(output.begin(),output.end(),str)==output.end())
                output.push_back(str);
            return;
        }
        for(int i=k;i<str.size();i++){
            swap(str[i],str[k]);
            Permutation2(output,str,k+1);
        }
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

注:将每个字符分别与第一个字符交换,然后递归即可,同时需要考虑去重。本题会从后往前递归。

数组中出现次数超过一半的数字

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if(numbers.size()==0)
            return 0;
        int count=1;
        int num=numbers[0];
        for(int i=1;i<numbers.size();i++){
            if(count==0){
                count=1;
                num=numbers[i];
                continue;
            }
            if(numbers[i]==num)
                count++;
            else
                count--;
            
        }
        count=0;
        for(int i=0;i<numbers.size();i++){
            if(numbers[i]==num)
                count++;
        }
    return count*2>numbers.size()?num:0;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

注:本题如果允许用额外空间可以使用hash表,但是最优解是空间复杂度为O(1),时间复杂度为O(n)。

最小的k个数

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        if(k<=0||k>input.size())
            return {};
        multiset<int,greater<int>> leastnum;
        for(int i=0;i<input.size();i++){
            if(leastnum.size()<k)
                leastnum.insert(input[i]);
            else{
                if(*leastnum.begin()>input[i]){
                    leastnum.erase(*leastnum.begin());
                    leastnum.insert(input[i]);
                }
            }
        }
        return vector<int>(leastnum.begin(),leastnum.end());
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

注:multiset集合 利用仿函数改变排序顺序 时间复杂度O(nlogk),这种方法处理大量数据有优势。

连续子数组的最大和

HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)

class Solution {
public:
    int FindGreatestSumOfSubArray(vector<int> array) {
        int cache=INT_MIN,sum=0;
        for(int i=0;i<array.size();i++){
            sum+=array[i];
            cache=max(cache,sum);
            if(sum<0)
                sum=0;
        }
        return cache;
    
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

注:使用sum记录增量和,当sum<0时代表无论之后的序列为何值,加上之前的序列都会变小,所以当sum<0时令temp=0。

整数中1出现的次数

求出1-13的整数中1出现的次数,并算出100-1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        if(n<=0)
            return 0;
        int count=0,a;
        for(int i=1;i<=n;i=i*10){
            int k=n%(i*10);
            if(k>i*2-1)
                a=i;
            else if(k<i)
                a=0;
            else
                a=k-i+1;
            count+=n/(i*10)*i+a;
        }
        return count;
    
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

注:要取余和整除它的10倍。归纳法:现在说十位数,十位数上出现1的情况应该是10-19,依然沿用分析个位数时候的阶梯理论,我们知道10-19这组数,每隔100出现一次,这次我们的阶梯是100,例如数字317,分析有阶梯0-99,100-199,200-299三段完整阶梯,每一段阶梯里面都会出现10次1(从10-19),最后分析露出来的那段不完整的阶梯。我们考虑如果露出来的数大于19,那么直接算10个1就行了,因为10-19肯定会出现;如果小于10,那么肯定不会出现十位数的1;如果在10-19之间的,我们计算结果应该是k - 10 + 1。例如我们分析300-317,17个数字,1出现的个数应该是17-10+1=8个。

把数组排成最小的数

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        if(numbers.size()==0)
            return "";
        sort(numbers.begin(),numbers.end(),mycompare);
        string s;
        for(int i=0;i<numbers.size();i++){
            s+=to_string(numbers[i]);
        }
        return s;
    }
    static bool mycompare(int a,int b){
        string A=to_string(a)+to_string(b);
        string B=to_string(b)+to_string(a);
        return A<B;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

注:两个数组合起来比较。

丑数

把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数

class Solution {
public:
    int GetUglyNumber_Solution(int index) {
        vector<int> output(index+1,1);
        auto ugly1=output.begin();
        auto ugly2=output.begin();
        auto ugly3=output.begin();
        for(int i=1;i<index;i++){
            output[i]=min3(*ugly1*2,*ugly2*3,*ugly3*5);
            if(output[i]==*ugly1*2)
                ugly1++;
            if(output[i]==*ugly2*3)//不能else if
                ugly2++;
            if(output[i]==*ugly3*5)
                ugly3++;
        }
        return output[index-1];
    
    }
    int min3(int a,int b,int c){
        a=min(a,b);
        return min(a,c);
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

注:使用空间换时间的方法,我们不需要挨个判断丑数,只需要找2/3/5他们三个的乘积从小到大排列就可以了,定义三个指针和一个数组记录从小到大的乘积(也就是丑数)即可。

第一个只出现一次的字符

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        if(str=="")
            return -1;
        unordered_map<char,int> hash;//这是char不是string,因为取出来的是char型
        for(int i=0;i<str.size();i++){
                hash[str[i]]++;
        }
        for(int i=0;i<str.size();i++){
            if(hash[str[i]]==1)
                return i;//这个不是i+1,因为题中可以取到0.
        }
        return -1;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

注:使用空间换时间,定义哈希表遍历一次,然后再验证一次即可。

数组中的逆序对

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

void Merge(vector<int> &data,int left,int right){
        // copy=data;如果在这拷贝就不需要最下面那个给copy赋值了,但是每次拷贝复制会超出时间限制
         
        int mid=(left+right)/2;
        int i=mid,j=right,k=right;
        while(i>=left&&j>=mid+1){
           
            if(copy[i]>copy[j]){
                data[k--]=copy[i--];
                count+=j-mid;
            }
            else
                data[k--]=copy[j--];
            
        }
        while(i>=left){
                data[k--]=copy[i--];//踏马这俩while放到上面那个while上面了,又找了一上午bug
            }
            while(j>=mid+1){
                data[k--]=copy[j--];
            }
        for(int i=left;i<=right;i++)
            copy[i]=data[i];
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

注:利用归并排序的思想找逆序对即可,需要注意num得设置为longlong类型。

两个链表的第一个公共节点

输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if(!pHead1||!pHead2)
            return nullptr;
        int len1=Getlen(pHead1);
        int len2=Getlen(pHead2);
        if(len1>len2)
            pfront(pHead1,len1-len2);
        else
            pfront(pHead2,len2-len1);
        while(pHead1&&pHead2){
            if(pHead1==pHead2)
                return pHead1;
            pHead1=pHead1->next;
            pHead2=pHead2->next;
        }
        return nullptr;
    }
    int Getlen(ListNode* p){
        int num=0;
        while(p){
            p=p->next;
            num++;
        }
        return num;
    }
    void pfront(ListNode*&p,int len){
        while(len){
            p=p->next;
            len--;
        }
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

注:先计算链表的长度,然后使用快慢指针在链表上,快指针比慢指针先走了两链表长度之差。还有一种是将两个链表全部压入栈,从尾结点开始对比,如果不同则输出后一个节点。

数字在排序数组中出现的次数。

统计一个数字在排序数组中出现的次数。

class Solution {
public:
    int GetNumberOfK(vector<int> data ,int k) {
        int len=data.size();
        if(len==0)
            return 0;
        int left=0,right=len-1;
        while(left<=right){
            int mid=(left+right)/2;
            if(data[mid]<k)
                left=mid+1;
            else
                right=mid-1;
        }
        if(left>len-1||data[left]!=k)//越界检查和是否存在检查
            return 0;
        int n1=left;
        right=len-1;
        while(left<=right){
            int mid=(left+right)/2;
            if(k<data[mid])
                right=mid-1;
            else
                left=mid+1;
        }
        return right-n1+1;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

注:应用二分查找法,找到第一个出现和最后一个出现的索引,然后相减即可。

二叉树的深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot==nullptr)
            return 0;
        int left=1+TreeDepth(pRoot->left);
        int right=1+TreeDepth(pRoot->right);
        int maxium=max(left,right);
        return maxium;
    
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

注:递归求解即可。

平衡二叉树

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth=0;
        return IsBalanced(pRoot,depth);

    }
    bool IsBalanced(TreeNode* pRoot,int &depth){//这里必须得引用,否则一直会是0
        if(pRoot==nullptr)
            return true;
        int leftdepth=depth,rightdepth=depth;
        bool left=IsBalanced(pRoot->left,leftdepth);
        bool right=IsBalanced(pRoot->right,rightdepth);
        depth=1+max(leftdepth,rightdepth);
        return left&&right&&(abs(leftdepth-rightdepth))<=1;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注:递归返回bool类型不是int类型,把depth每次都传入即可,注意要用引用传参。

数组中只出现一次的数字

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字

class Solution {
public:
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
        if(data.size()==0||data.size()==1)
            return;
        int cache=0;
        for(int i=0;i<data.size();i++){
            cache^=data[i];
        }
        int index=findbit1(cache);
        for(int i=0;i<data.size();i++){
            if(isbit1(data[i],index))
                *num1^=data[i];
            else
                *num2^=data[i];
        }
        return;

    }
    int findbit1(int cache){
        int index=0;
        while(cache^1){
            cache=cache>>1;
            index++;
        }
        return index;
    }
    bool isbit1(int a,int b){
        return a>>b&1;
    }
    
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

注:异或思想,如果面试时没思路直接就用哈希表。

和为s的连续正数序列

小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {
        vector<vector<int>> output;
        int left=1,right=2;
        while(left<=sum/2&&left<right){
            if((left+right)*(right-left+1)<sum*2)
                right++;
            else if((left+right)*(right-left+1)>sum*2)
                left++;
            else{
                vector<int> cache;
                for(int i=left;i<=right;i++)
                    cache.push_back(i);
                output.push_back(cache);
                left=left+2;
                right++;
            }
        }
        return output;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

注:双指针从头开始遍历,注意截至条件。

和为s的两个数字

输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

class Solution {
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        if(array.size()<=1)
            return {};
        int left=0,right=array.size()-1;
        int num1,num2,maximun=INT_MAX;
        while(left<right){
            if(array[left]+array[right]<sum)
                left++;
            else if(array[left]+array[right]>sum)
                right--;
            else{
                int num=array[left]*array[right];
                maximun=min(maximun,num);
                if(num==maximun){
                    num1=array[left];
                    num2=array[right];
                }
                left++;
                right--;
            }
        }
        if(maximun==INT_MAX)//注意不存在判断
            return{};
        return {num1,num2};
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

注:本题的数组是连续的,所以是典型的双指针算法应用场景,分别设定左右指针在数组的首尾,两数之和大于target,则right指针自减,反之则left指针自加,由于本题还需要求最小的成绩,所以还需要引入哨兵。本题测试用例不考虑乘积越界。

左旋转字符串

汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

class Solution {
public:
    string LeftRotateString(string str, int n) {
        if(str=="")
            return "";
        reverse(str.begin(),str.begin()+n);
        reverse(str.begin()+n,str.end());
        reverse(str.begin(),str.end());
        return str;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

注:两极反转

翻转单词顺序列

牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

class Solution {
public:
    string ReverseSentence(string str) {
        reverse(str.begin(),str.end());
        int left=0,right=1;
        while(right<str.size()){
            while(right<str.size()&&str[right]!=' ')//' '应该打空格的,否则等于空字符
                right++;
            reverse(str.begin()+left,str.begin()+right);
            right++;
            left=right;
        }
        return str;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注:先翻转整个字符串,然后再翻转每一个单词。

扑克牌顺子

LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张_)…他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子…LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。

class Solution {
public:
    bool IsContinuous( vector<int> numbers ) {
        if(numbers.size()<5)
            return false;
        sort(numbers.begin(),numbers.end());
        int count=0,num=0;
        for(int i=0;i<numbers.size()-1;i++){
            if(numbers[i]==0)
                count++;
            else{
                if(numbers[i]==numbers[i+1])
                    return false;
                num+=numbers[i+1]-numbers[i]-1;
            }
        }
        if(count>4)
            return false;
        return num<=count?1:0;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

注:先将数组进行排序,然后从前往后遍历,看看0的数量是不是能填补空缺。

圆圈中最后剩下的数

每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0…m-1报数…这样下去…直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1) 如果没有小朋友,请返回-1

class Solution {
public:
    int LastRemaining_Solution(int n, int m)
    {
        if(n<=0)
            return -1;
        list<int> l;
        for(int i=0;i<n;i++){
            l.push_back(i);
        }
        auto it=l.begin();
        while(l.size()>1){
            for(int i=1;i<m;i++){//i从1开始
                it++;
                if(it==l.end())
                    it=l.begin();
            }
            auto it1=it;
            it++;
            if(it==l.end())
                it=l.begin();
            l.erase(it1);
        }
        return *it;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

注:使用list模拟环形链表。

求1+2+3+…+n

求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

class Temp{
    public:
    Temp(){
        N++;
        sum+=N;
    }
    Temp(int a){
        N=0;
        sum=0;
    }
    static int getval(){
        return sum;
    }
    static int N;
    static int sum;
};
int Temp::N=0;
int Temp::sum=0;
class Solution {
public:
    int Sum_Solution(int n) {
        Temp A(0);//这里归0,否则通过第一个测试案例之后不会归0便进入下一个测试案例
        Temp *p=new Temp[n];
        delete []p;
        p=nullptr;
        return Temp::getval();
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

注:利用静态变量和类的无参构造

不用加减乘除做加法

写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号.

class Solution {
public:
    int Add(int num1, int num2)
    {
        int a=num1;
        while(num2!=0){
            a=num1^num2;
            int b=(num1&num2)<<1;
            num1=a;
            num2=b;
        }
        return a;

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注:采用三步走的方式,首先第一步用异或相加但不进位,第二步求与左移一位算进位,第三步相加,循环即可。

把字符串转换成整数

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。数值为0或者字符串不是一个合法的数值则返回0

class Solution {
public:
    int StrToInt(string str) {
        bool flag=true;
        if(str.size()==0){
            flag=false;
            return 0;
        }
        long long num=0;//8字节,否则下面超范围会返回4字节的最大值
        int sign=1;
        if(str[0]=='+')
            sign=1;
        else if(str[0]=='-')
            sign=-1;
        else if(str[0]>='0'&&str[0]<='9')
            num=str[0]-'0';
        else{
            flag=false;
            return 0;
        }
        for(int i=1;i<str.size();i++){
            if(str[i]>='0'&&str[i]<='9')
                {num=num*10+str[i]-'0';
                if((sign==1&&num>0x7FFFFFFF)||(sign==-1&&(-1*num)<(signed int)0x80000000))//这里范围品一下
                return 0;}
            
            else{
                flag=false;
                return 0;
            }
            
        }
        return sign*num;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

注:注意各种边界条件即可,题目不能全部AC(超过了最小负数了),本题中考虑num越界以及正负号非法的测试用例

数组中重复的数字

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

class Solution {
public:
    // Parameters:
    //        numbers:     an array of integers
    //        length:      the length of array numbers
    //        duplication: (Output) the duplicated number in the array number
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    bool duplicate(int numbers[], int length, int* duplication) {
        for(int i=0;i<length;i++){
            while(numbers[i]!=i){
                if(numbers[numbers[i]]==numbers[i]){
                    *duplication=numbers[i];
                    return true;
                }
                else
                    swap(numbers[i],numbers[numbers[i]]);
            }
        }
        return false;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

注:利用数组下标和数组的值的关系

构建乘积数组

给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * … * A[n-1],B[n-1] = A[0] * A[1] * … * A[n-2];)

class Solution {
public:
    vector<int> multiply(const vector<int>& A) {
        if(A.size()==0)
            return {};
        vector<int> B1(A.size(),1);
        vector<int> B2(A.size(),1);
        vector<int> B(A.size(),1);
        for(int i=1;i<A.size();i++){
            B1[i]=A[i-1]*B1[i-1];
        }
        for(int i=A.size()-2;i>=0;i--){
            B2[i]=A[i+1]*B2[i+1];
        }
        for(int i=0;i<A.size();i++){
            B[i]=B1[i]*B2[i];
        }
    return B;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

注:分成两个数组相乘即可。

正则表达式匹配

请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if(!str||!pattern)
            return false;
        if(*str=='\0'&&*pattern=='\0')
            return true;
        if(*str!='\0'&&*pattern=='\0')
            return false;
        if(*(pattern+1)=='*'){
            if(*str==*pattern||(*pattern=='.'&&*str!='\0'))
                return match(str+1,pattern+2)||match(str+1,pattern)||match(str,pattern+2);//即使相等也可能忽视*继续向下比较
            
            else return match(str,pattern+2);
            
            }
         if (*str==*pattern||(*pattern=='.'&&*str!='\0'))
                return match(str+1,pattern+1);//一定都要加return,否则内存超限,只能写+1不能写++,因为这里面没有分号,这出了半天bug
            return false;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

注:这种题首先就要考虑特殊条件,即下一个字符为*时的情况,随后递归各条件即可。

表示数字的字符串

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。

class Solution {
public:
    bool isNumeric(char* string)
    {
        if(!string)
            return false;
        bool numh=isnumber(&string);
        if(*string=='.'){
            string++;
            numh=isnumber2(&string)||numh;}
        if(!numh)
            return false;
        if(*string=='E'||*string=='e'){
            string++;
            numh=isnumber(&string);
        }
        return numh&&(*string=='\0');
    }
    bool isnumber(char** str) {
        if (**str == '+' || **str == '-')
           (*str)++;
        return isnumber2(str);//这里是str不是&str,因为这里已经是二级指针,str代表二级地址,如果再传&str下面应该用三级指针来接收,这里二级指针产生拷贝没有关系,一级指针不会拷贝。

    }
    bool isnumber2(char** str) {
        char* before = *str;//*str
        while (**str != '\0' && **str >= '0' && **str <= '9')//while
            (*str)++;//(*str)++不能是*str++
        return *str > before;
    }

};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

注:这里唯一需要注意的就是使用指针的指针。

字符流中第一个不重复的字符

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

class Solution
{
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
         s.push_back(ch);
        hash[ch]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        for(char ch:s){
            if(hash[ch]==1)
                return ch;
        }
        return '#';
    
    }
    private:
    string s;
    unordered_map<char,int> hash;

};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

注:使用哈希表

列表中环的入口节点

给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
        if(!pHead||pHead->next==nullptr)
            return nullptr;
        ListNode* p1=pHead->next->next;
        ListNode* p2=pHead;
        while(p1!=p2){
            if(p1==nullptr||p1->next==nullptr)
                return nullptr;
            p1=p1->next->next;
            p2=p2->next;
        }
        int count=1;
        p1=p1->next;
        while(p1!=p2){
            count++;
            p1=p1->next;
        }
        p1=pHead;
        while(count){
            p1=p1->next;
            count--;
        }
        p2=pHead;
        while(p1!=p2){
            p1=p1->next;
            p2=p2->next;
        }
        return p1;

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

注:首先使用快慢(快的步长是慢的二倍)指针判断有没有环,如果有快慢指针一定会相交,其次找到相交点计算环的长度,然后根据环的长度再次使用快慢指针(快指针比慢指针先走了环的长度大小,步长均为1)即可找到环的入口。

删除链表中重复的节点

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        if(pHead==nullptr)
            return nullptr;
        ListNode* m=new ListNode(0);
        m->next=pHead;
        ListNode* p=m;
        ListNode* q=pHead;
        while(q&&q->next){
            if(q->val==q->next->val)
                q=q->next;
            else{
                if(p->next==q)
                    p=p->next;
                else{
                    p->next=q->next;
                    q=q->next;
                }
            }
        }
        if(p->next!=q)//防止111111出现
            p->next=nullptr;
        return m->next;

    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

注:找规律的链表题,不是去重是删重

二叉树的下一个节点

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

/*
struct TreeLinkNode {
    int val;
    struct TreeLinkNode *left;
    struct TreeLinkNode *right;
    struct TreeLinkNode *next;
    TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
        
    }
};
*/
class Solution {
public:
    TreeLinkNode* GetNext(TreeLinkNode* pNode)
    {
        if(pNode==nullptr)
            return nullptr;
        if(pNode->right){
            pNode=pNode->right;
            while(pNode->left)
                pNode=pNode->left;
            return pNode;
        }
        while(pNode->next){
            TreeLinkNode* pNode1=pNode->next;
            if(pNode1->left==pNode)
                return pNode1;
            pNode=pNode->next;
        }
        return nullptr;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

注:我们可分成两大类:1、有右子树的,那么下个结点就是右子树最左边的点; 2、没有右子树的,也可以分成两类,a)是父节点左孩子 ,那么父节点就是下一个节点 ; b)是父节点的右孩子找他的父节点的父节点的父节点…直到当前结点是其父节点的左孩子位置。如果没有eg:M,那么他就是尾节点。

对称的二叉树

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    bool isSymmetrical(TreeNode* pRoot)
    {
        if(pRoot==nullptr)
            return true;//空树为真
        return isSymmetrical(pRoot->left,pRoot->right);
    }
    bool isSymmetrical(TreeNode* pRoot1,TreeNode* pRoot2){
        if(pRoot1==nullptr&&pRoot2==nullptr)
            return true;
        if(pRoot1==nullptr||pRoot2==nullptr)
            return false;
        if(pRoot1->val!=pRoot2->val)
            return false;
        return isSymmetrical(pRoot1->left,pRoot2->right)&&isSymmetrical(pRoot1->right,pRoot2->left);
    }

};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

注:递归判断两个子树,左子树等于右子树,右子树等于左子树即可。

按之字形顺序打印二叉树

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        if(pRoot==nullptr)
            return {};
        vector<vector<int> > output;
        vector<int> cache;
        stack<TreeNode*> s1,s2;
        s1.push(pRoot);//这里存的是指针
        bool flag=true;
        while(!s1.empty()||!s2.empty()){
            if(flag){
                int size=s1.size();
                
                while(size){
                    
                    TreeNode* p=s1.top();
                    cache.push_back(p->val);
                    if(p->left)
                        s2.push(p->left);//这要压s2的栈
                    if(p->right)
                        s2.push(p->right);
                    s1.pop();
                    size--;
                }
                flag=!flag;
            }
            else{
                int size=s2.size();
                   while(size){
                    TreeNode* p=s2.top();
                    cache.push_back(p->val);
                    if(p->right)//先压右树
                        s1.push(p->right);
                    if(p->left)
                        s1.push(p->left);
                    s2.pop();
                    size--;
                }
                flag=!flag;
            }
            output.push_back(cache);
            cache.clear();
        }
        return output;
    }
    
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

注:使用两个栈即可,一个先压入左子树,一个先压入右子树。

把二叉树打印成多行

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            if(pRoot==nullptr)
                return {};
            vector<vector<int> > output;
            vector<int> cache;
            int num=1,count=0;
            queue<TreeNode*> q;
            q.push(pRoot);
            while(!q.empty()){
                TreeNode* p=q.front();
                cache.push_back(p->val);
                if(p->left){
                    q.push(p->left);
                    count++;
                }
                if(p->right){
                    q.push(p->right);
                    count++;
                }
                q.pop();
                num--;
                if(num==0){
                    output.push_back(cache);
                    cache.clear();
                    num=count;
                    count=0;
                    }
            }
        return output;
        }
    
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

注:用两个变量保存当前行打印的数量和下一行要打印的数量

序列化二叉树

请实现两个函数,分别用来序列化和反序列化二叉树

二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。
二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
例如,我们可以把一个只有根节点为1的二叉树序列化为"1,",然后通过自己的函数来解析回这个二叉树

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    char* Serialize(TreeNode *root) {    
        string s;
        TreeNode *pRoot=root;
        if (!pRoot)
            return NULL;
        deque<TreeNode*> q;
        q.push_back(pRoot);
        while (!q.empty()) {
            int n = q.size();
            for (int i = 0; i < n; ++i) {
                if (q.front()) {
                    q.push_back(q.front()->left);
                    q.push_back(q.front()->right);
                    s += to_string(q.front()->val) + ' ';
                } else {
                    s += "# ";
                }
                q.pop_front();
            }
        }
        char* chr = strdup(s.c_str());
        return  chr;
    }
    TreeNode* Deserialize(char *str) {
 if (!str)
            return nullptr;
        int k = 0;
        auto ret = nextNode(str, k);
        deque<TreeNode*> q;
        q.push_back(ret);
        while (!q.empty()) {
            int n = q.size();
            for (int i = 0; i < n; ++i) {               
                q.front()->left = nextNode(str, k);
                q.front()->right = nextNode(str, k);
                if (q.front()->left)
                    q.push_back(q.front()->left);
                if (q.front()->right)
                    q.push_back(q.front()->right);
                q.pop_front();
            }
        }
        return ret;
    }
TreeNode* nextNode(char *str,int &i) {
        string s;
        while (str[i] != '\0'&&str[i] != ' ') {
            if (str[i] == '#') {
                i += 2;
                return nullptr;
            }
            s += str[i];
            i++;
        }
        if (str[i] == ' ')
            i++;
        if (!s.empty())
            return new TreeNode(stoi(s));
        return nullptr;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

注:放弃

二叉搜索时的第k个节点

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(k<=0||pRoot==nullptr)
            return nullptr;
        vector<TreeNode*> cache;
        Inorder(pRoot,cache);
        if(cache.size()<k)
            return nullptr;
        return cache[k-1];
    }
    void Inorder(TreeNode* pRoot,vector<TreeNode*>& cache){//,  ,傻傻分不清楚
        if(pRoot->left)
            Inorder(pRoot->left,cache);
        cache.push_back(pRoot);
        if(pRoot->right)
            Inorder(pRoot->right,cache);
    } 
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

注:中序遍历标准递归

数据流中的中位数

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

class Solution {
public:
    void Insert(int num)
    {
        if ((max.size() + min.size()) & 1) {
            if (min.size() > 0 && num > min[0]) {
                min.push_back(num);
                push_heap(min.begin(), min.end(), greater<int>());//heap不是head
                num = min[0];
                pop_heap(min.begin(), min.end(), greater<int>());
                min.pop_back();
            }
            max.push_back(num);
            push_heap(max.begin(), max.end(), less<int>());//greater<int>()这个要加括号记住先

        }
        else {
            if (max.size() > 0 && num < max[0]) {
                max.push_back(num);
                push_heap(max.begin(), max.end(), less<int>());
                num = max[0];
                pop_heap(max.begin(), max.end(), less<int>());
                max.pop_back();
            }
            min.push_back(num);
            push_heap(min.begin(), min.end(), greater<int>());
        }
    }

    double GetMedian()
    {
        bool flag = false;
        if (max.size() + min.size() == 0)
        {
            flag = true;
            return 0;
        }
        if ((max.size() + min.size()) & 1)
            return min[0];
        else
            return double((max[0] + min[0])) / 2;//除以2要放在最外面,不能用<<代替


    }
private:
    vector<int> max;
    vector<int> min;

};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

注:大根堆,小根堆的用法。

滑动窗口的最大值

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。

class Solution {
public:
    vector<int> maxInWindows(const vector<int>& num, unsigned int size)
    {
        if(num.size()<size||size<=0)
            return {};
        vector<int> v;
        deque<int> d;
        for(int i=0;i<size;i++){
            while(!d.empty()&&num[i]>num[d.back()])
                d.pop_back();
            d.push_back(i);
        }
        for(int i=size;i<num.size();i++){
            v.push_back(num[d.front()]);
            while(!d.empty()&&num[i]>num[d.back()])
                d.pop_back();
            if(!d.empty()&&i-size>=d.front())
                d.pop_front();
            d.push_back(i);
        }
        v.push_back(num[d.front()]);
        return v;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

注:双端队列,保存的是下标不是值很精彩。

矩阵中的路径

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 [abce sfcs adee ]

\quad⎣⎡​asa​bfd​cce​ese​⎦⎤​ 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子

class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if(!matrix||!str)
            return false;
        vector<int> cache(rows*cols,0);
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                if(Path(matrix,cache,i,j,rows,cols,str))
                    return true;
            }
        }
        return false;
    
    }
    bool Path(char* matrix, vector<int> &cache,int i,int j,int rows, int cols, char* str){
        if(*str=='\0')//输入为一个A时
            return true;
        if(*(matrix+i*cols+j)==*str&&cache[i*cols+j]==0){
            cache[i*cols+j]=1;
            if((i-1>=0&&Path(matrix,cache,i-1,j,rows,cols,str+1))
               ||(i+1<rows&&Path(matrix,cache,i+1,j,rows,cols,str+1))
               ||(j-1>=0&&Path(matrix,cache,i,j-1,rows,cols,str+1))
               ||(j+1<cols&&Path(matrix,cache,i,j+1,rows,cols,str+1)))
                return true;
            if(*(str+1)=='\0')//记住
                return true;
            cache[i*cols+j]=0;
        }
        return false;
    }


};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

注:在所有路径当中挨个递归查询。

机器人的运动范围

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

class Solution {
public:
    int movingCount(int threshold, int rows, int cols)
    {
        if(threshold<0||rows<0||cols<0)
            return 0;
        vector<vector<int> >cache(rows,vector<int>(cols,0));
        int num=0;
        num=Pathcount(cache,threshold,0,0,rows,cols);
        return num;
    }
    int Pathcount(vector<vector<int> >&cache,int threshold,int row,int col,int rows,int cols){
        if(row<0||col<0||row>=rows||col>=cols||cache[row][col]==1||sumnum(row)+sumnum(col)>threshold)//sumnum(row)+sumnum(col)
            return 0;
        cache[row][col]=1;
        return 1+
            Pathcount(cache,threshold,row+1,col,rows,cols)+
            Pathcount(cache,threshold,row,col+1,rows,cols)+
            Pathcount(cache,threshold,row-1,col,rows,cols)+
            Pathcount(cache,threshold,row,col,rows,cols);
    }
    int sumnum(int a){
        int sum=0;
        while(a){
        int b=a%10;
        a=a/10;
        sum+=b;}
        return sum;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

注:跟上题一样的思路,不过增加了额外的限制条件。

剪绳子

给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],…,k[m]。请问k[0]xk[1]x…xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18

class Solution {
public:
    int cutRope(int number) {
        if(number==2)
            return 1;
        if(number==3)
            return 2;
        vector<int> cache(number+1,2);
        cache[3]=3;
        for(int i=4;i<=number;i++)//<=
            cache[i]=cache[i-2]*2;
        return cache[number];
        
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
class Solution {
public:
    int cutRope(int number) {
        if(number<2)
            return 0;
        if(number==2)
            return 1;
        if(number==3)
            return 2;//这是2
        vector<int> cache(number,0);
        cache[0]=0;
        cache[1]=1;
        cache[2]=2;
        cache[3]=3;
        int max1;
        for(int i=4;i<=number;i++){
            max1=0;
            for(int j=1;j<=i/2;j++){
                int c=cache[j]*cache[i-j];//int cache和上面的max都报错,不能瞎起名
                max1=max(max1,c);
            }
            cache[i]=max1;
        }
        return cache[number];
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

注:动态规划,我感觉他最大就是前第二个数*2但没有理论支持,标准解法为第二个解法。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号