天天看点

剑指offer刷题集锦(C++版本)

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

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int row = 0;
        int col = array[0].size() -  1;
        while (row <= array.size() - 1 && col >= 0){
            if (target == array[row][col]) return true;
            else if(target > array[row][col]) row++;
            else  col--;
        }
        return false;
        
        
    }
};
           

2.请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。注:"a"和’a’的区别,前者是字符串,后者是字符。

class Solution {
public:
	void replaceSpace(char *str,int length) {
        int i=0;
        while(str[i]!='\0')
        {
            if(str[i]==' ')
            {
                for(int j=length-1;j>i;j--)
                {
                    str[j+2]=str[j];
                }
                str[i+2]='0';
                str[i+1]='2';
                str[i]='%';
                length+=2;
                i=i+2;
            }
            else
            {
                i++;
            }
        }
	}
};
           

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

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> result;
        while(head!=NULL){
            result.push_back(head->val);
            head=head->next;
        }
        reverse(result.begin(),result.end());
        return result;
    }
};
           

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) {
        int len=vin.size();
        if (len==0)
            return NULL;
        vector<int> left_pre,right_pre,left_vin,right_vin;
        TreeNode* head = new TreeNode(pre[0]);
        int gen = 0;
        for(int i=0;i<len;i++)
        {
            if(vin[i]==pre[0])
            {
                gen = i;
                break;
            }
        }
        for(int i=0;i<gen;i++)
        {
            left_pre.push_back(pre[i+1]);
            left_vin.push_back(vin[i]);
        }
        for(int i=gen+1;i<len;i++)
        {
            right_pre.push_back(pre[i]);
            right_vin.push_back(vin[i]);
        }
        head->left = reConstructBinaryTree(left_pre,left_vin);
        head->right = reConstructBinaryTree(right_pre,right_vin);
        return head;
    }
};
           

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

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

    int pop() {
        int value;
        if (stack2.size()){
            value = stack2.top();
            stack2.pop();
        }
        else{
            while(stack1.size()){
                int element = stack1.top();
                stack2.push(element);
                stack1.pop();
            }
             value = stack2.top();
             stack2.pop();
        }
        return value;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
           

6.把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{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 min = rotateArray[0];
        for(int i=1;i<rotateArray.size();i++){
            if(rotateArray[i]<min){
                min = rotateArray[i];
                break;
            }
        }
        return min;
    }
};
           

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

class Solution {
public:
    int Fibonacci(int n) {
        if(n==0)
            return 0;
        else if(n==1)
            return 1;
        else{
            int a = 0;
            int b = 1;
            int temp;
            while(n>1)
            {
                temp = a;
                a = b;
                b = temp+b;
                n--;
            }
            return b;
        }
    }
};
           

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

class Solution {
public:
    int jumpFloor(int number) {
        if(number==1)
            return 1;
        else if(number==2)
            return 2;
        else{
            return jumpFloor(number-1)+jumpFloor(number-2);
        }
    }
};

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

class Solution {
public:
    int jumpFloorII(int number) {
        if(number==0)
            return number;
        int total=1;
        for(int i=1;i<number;i++)
            total*=2;
        return total;
    }
};

           

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

class Solution {
public:
    int rectCover(int number) {
        if(number==0)
            return 0;
        else if(number==1)
            return 1;
        else if(number==2)
            return 2;
        else{
            int a = 1;
            int b = 2;
            int temp;
            while(number>2)
            {
                temp = a;
                a = b;
                b = temp+b;
                number--;
            }
            return b;
        }
    }
};
           

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

class Solution {
public:
     int  NumberOf1(int n) {
         int result = 0;
         unsigned int flag = 1;
         while(flag)
         {
             if(n&flag)
                 result++;
             flag = flag<<1;
         }
         return result;
     }
};
           

11.给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

class Solution {
public:
    double Power(double base, int exponent) {
        double result=1;
        if(exponent>0)
        {
            for(int i=1;i<=exponent;i++)
            {
                result = result*base;
            }
        }
        else if(exponent==0)
        {
            return 1;
        }
        else{
            base=1/base;
            for(int i=1;i<=abs(exponent);i++)
            {
                result = result*base;
            }
        }
        return result;
    }
};
           

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

class Solution {
public:
    void reOrderArray(vector<int> &array) {
        vector<int> result;
        int num=array.size();
        for(int i=0;i<num;i++)
            {
            if(array[i]%2==1)
                result.push_back(array[i]);
        }
        for(int i=0;i<num;i++)
            {
            if(array[i]%2==0)
                result.push_back(array[i]);
        }
        array=result;
    }
};
           

13.输入一个链表,输出该链表中倒数第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) {
        ListNode* p = pListHead;
        for (unsigned int i=  0;i < k;i++){
            if (p == NULL)
                return NULL;
            else 
                p = p->next;
        }
        while(p!=NULL){
            p = p->next;
            pListHead = pListHead->next;
        }
        return pListHead;
    }
};
           

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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* temp;
        ListNode* p=NULL;
        while (pHead){
            temp = pHead->next;
            pHead->next = p;
            p = pHead;
            pHead = temp;
        }
        return p;

    }
};
           

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

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode* phead = new ListNode(0);
        ListNode* list_new = phead;
        while (pHead1 || pHead2){
            if (pHead1 == NULL){
                list_new->next = pHead2;
                break;
            }
            else if (pHead2 == NULL){
                list_new->next = pHead1;
                break;
            }
            if ((pHead1->val) > (pHead2->val)){
                list_new->next = pHead2;
                pHead2 = pHead2->next;
            }
            else{
                list_new->next = pHead1;
                pHead1 = pHead1->next;
            }
            list_new = list_new->next;
        }
        return phead->next;  //不管第一个节点
    }  
};
           

16.输入两棵二叉树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 || !pRoot2)
            return false;
        return (dfs(pRoot1, pRoot2) ||HasSubtree(pRoot1->left,pRoot2) || HasSubtree(pRoot1->right,pRoot2));
    
    }
    bool dfs(TreeNode* R1, TreeNode* R2){
        if (!R2)
            return true;
        if (!R1)
            return false;
        if (R1->val != R2->val)
            return false;
        return dfs(R1->left, R2->left) && dfs(R1->right,R2->right);
    }
};
           

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

/*
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 == NULL)
            return ;
        TreeNode* temp = pRoot->left;
        pRoot->left = pRoot->right;
        pRoot->right = temp;
        Mirror(pRoot->left);
        Mirror(pRoot->right);
    }
};
           

18.输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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) {
        int cir = 0;
        int row = matrix.size();
        int col = matrix[0].size();
        vector<int> ans;
        while(row > 2 * cir && col > 2 * cir){
            for (int i = cir; i <= col - cir - 1; i++)
                ans.push_back(matrix[cir][i]);
            if (cir < row - cir - 1){
                for (int i = cir + 1; i <= row - cir - 1;i++)
                    ans.push_back(matrix[i][col - cir - 1]);
            }
            if(col-cir-1>cir && row-1-cir>cir){
                for(int i=col-cir-2;i>=cir;i--)
                    ans.push_back(matrix[row-1-cir][i]);
            }

            if(cir<col-cir-1 && cir<row-cir-2){
                for(int i = row-cir-2;i>=cir+1;i--)
                    ans.push_back(matrix[i][cir]);
            }
            cir++;
        }
        return ans;

    }
};
           

19.定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

class Solution {
public:
    void push(int value) {
        if (minstack.empty() || value < minstack.top())
            minstack.push(value);
        else
            minstack.push(minstack.top());
        stack1.push(value);
    }
    void pop() {
        stack1.pop();
        minstack.pop();
    }
    int top() {
        return stack1.top();
    }
    int min() {
        return minstack.top();
    }
private:
    stack<int> stack1;
    stack<int> minstack;
};
           

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

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
       stack<int> st;
        int id=0;
        for(int i = 0;i<pushV.size();i++){
           while (st.empty() || st.top() != popV[i]){
               st.push(pushV[id++]);
           }
       }
    }
};
           

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

/*
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) {
        TreeNode* fr;
        vector<int> result;
        queue<TreeNode*> Q;
        if (root == NULL) return result ;
        Q.push(root);
        while(!Q.empty()){
            fr = Q.front();
            result.push_back(fr->val);
            if (fr->left!=NULL)
                Q.push(fr->left);
            if (fr->right!=NULL)
                Q.push(fr->right);
            Q.pop();
        }
        return result;
    }
};
           

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

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        if(sequence.empty())
            return false;
        int index;
        int begin = 0;
        int end = sequence.size()-1;
        int root = sequence[end];
        for(index = begin;index<end;index++)
            if(sequence[index]>root)
                break;
        for(int j = index;index<end;index++)
            if(sequence[index]<root)
                return false;
        bool left = true;
        vector<int> left_sq(sequence.begin(),sequence.begin()+index);
        if(index>begin)
            left = VerifySquenceOfBST(left_sq);
        bool right = true;
        vector<int> right_sq(sequence.begin()+index+1,sequence.end());
        if(index<end-1)
            right = VerifySquenceOfBST(right_sq);
        return left&&right;
    }
};
           

24.输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的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>> result;
    vector<int> temp;
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root==NULL)
            return result;
        temp.push_back(root->val);
        if(expectNumber-root->val==0 && root->left==NULL && root->right==NULL)
            result.push_back(temp);
        FindPath(root->left,expectNumber-root->val);
        FindPath(root->right,expectNumber-root->val);
        if(temp.size()>0)
            temp.pop_back();
        return result;
    }
};
           

25.输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

/*
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==NULL)
            return NULL;
        RandomListNode* cur;
        cur = pHead;
        while(cur){
            RandomListNode* node = new RandomListNode(cur->label);
            node->next = cur->next;
            cur->next = node;
            cur = node->next;
        }//新链表和就链表链接:A->A'->B->B'->C->C'
        cur = pHead;
        RandomListNode* p;
        while(cur){
            p = cur->next;
            if(cur->random)
                p->random = cur->random->next; //关键
            cur = p->next;
        }
        RandomListNode* temp;
        RandomListNode* phead = pHead->next;
        cur = pHead;
        while(cur->next){
            temp = cur->next;
            cur->next = temp->next;
            cur = temp;
        }
        return phead;
    }
};
           

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

/*
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)
    {
        stack<TreeNode*> st;
        TreeNode *cur = pRootOfTree;
        TreeNode *pre = pRootOfTree;
        TreeNode *head = pRootOfTree;
        bool isFirst = true;
        while(cur||!st.empty())
        {
            while(cur)
            {
                st.push(cur);
                cur = cur->left;
            }
            cur = st.top();
            st.pop();
            if(isFirst)
            {
                head = pre = cur;
                isFirst = false;
            }
            else
            {
                pre->right = cur;
                cur->left = pre;
                pre = cur;
            }
            cur = cur->right;
        }
        return head;
    }
};
           

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

class Solution {
public:
    vector<string> result;
    vector<string> Permutation(string str) {
        if(str.length()==0)
            return result;
        permutation1(str,0);
        sort(result.begin(),result.end());
        return result;
    }
    void permutation1(string str,int begin){
        if(begin==str.length())
        {
            result.push_back(str);
            return;
        }
        for(int i = begin;str[i]!='\0';i++)
        {
            if(i!=begin&&str[begin]==str[i])
                continue;
            swap(str[begin],str[i]);
            permutation1(str,begin+1);
            swap(str[begin],str[i]);
        }
    }
};
           

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

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        int length = numbers.size();
        if (length==0)
            return 0;
        sort(numbers.begin(),numbers.end());
        int num = numbers[0];
        int max_count = 1;
        int count = 0;
        for(int i = 1;i<length;i++)
        {
            if(numbers[i]!=numbers[i-1]){
                if(count>max_count)
                {
                    max_count = count;
                    num = numbers[i-1];
                }
                count = 1;
            }
            else
            {
                count++;
            }
        }
        if(max_count>length/2){
            return num;
        }
        else
            return 0;
    }
};
           

29输入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) {
        sort(input.begin(), input.end());
        vector<int >result;
        if (k >input.size()) return result;
        for (int i = 0; i <k ;i++)
            result.push)back
        return result;
    }
};
           

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

class Solution {
public:
    int FindGreatestSumOfSubArray(vector<int> array) {
        int temp_max = array[0];
        int max_num = array[0];
        for(int i=1;i<array.size();i++){
            temp_max=max(array[i],array[i]+temp_max);
            max_num = max(temp_max,max_num);
        }
        return max_num;
    }
};
           

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

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int temp = n;
        int last;
        int result = 0;
        int base = 1;
        while(temp){
            last = temp%10;
            temp = temp/10;
            result += temp*base;
            if (last==1){
                result += n%base + 1;
            }
            else if(last>1){
                result += base;
            }
            base *=10;
        }
        return result;
    }
};
           

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

class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        string res="";
        int length = numbers.size();
        if(length==0)
            return "";
        sort(numbers.begin(),numbers.end(),cmp);
        for(int i=0;i<length;i++)
            res += to_string(numbers[i]);
        return res;
    }
    static bool cmp(int a,int b){
        string A = to_string(a)+to_string(b);
        string B = to_string(b)+to_string(a);
        return A<B;
    }
};
           

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

class Solution {
public:
    int GetUglyNumber_Solution(int index) {
        if(index<7)
            return index;
        int t2=0,t3=0,t5=0;
        vector<int> res(index);
        res[0]=1;
        for(int i = 1;i<index;i++)
        {
            res[i] = min(res[t2]*2,min(res[t3]*3,res[t5]*5));
            if(res[i]==res[t2]*2)t2++;
            if(res[i]==res[t3]*3)t3++;
            if(res[i]==res[t5]*5)t5++;
        }
        return res[index-1];
    }
};
           

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

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        char result[256] = {0};
        int length = str.length();
        if (length<=0) return -1;
        for (int i = 0;i<length;i++)
            result[str[i]]++;
        for (int i = 0;i<length;i++){
            if (result[str[i]]==1)
                       return i;
        }
        return -1;
        
        
    }
};
           

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

36.输入两个链表,找出它们的第一个公共结点。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        ListNode* p1 = pHead1;
        ListNode* p2 = pHead2;
        int len1=0,len2=0,diff;
        while(p1){
            len1++;
            p1 = p1->next;
        }
        while(p2){
            len2++;
            p2 = p2->next;
        }
        if(len1>len2){
            diff = len1 - len2;
            p1 = pHead1;
            p2 = pHead2;
        }
        else{
            diff = len2-len1;
            p1 = pHead2;
            p2 = pHead1;
        }
        for(int i=0;i<diff;i++){
            p1 = p1->next;
        }
        while(p1!=NULL && p2!=NULL){
            if(p1==p2)
                break;
            p1 = p1->next;
            p2 = p2->next;
        }
        return p1;
    }
};
           

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

class Solution {
public:
    int GetNumberOfK(vector<int> data ,int k) {
        int count = 0;
        for(int i=0;i<data.size();i++){
            if(data[i]==k)
                count++;
        }
        return count;
    }
};
           

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

/*
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) return 0;
        return max(1+TreeDepth(pRoot->left),1+TreeDepth(pRoot->right));
    }
};
           

39.输入一棵二叉树,判断该二叉树是否是平衡二叉树。

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if (pRoot == NULL)
            return true;
        int left_depth = getDepth(pRoot->left);
        int right_depth = getDepth(pRoot->right);
        if (left_depth>right_depth+1 || left_depth+1<right_depth)
            return false;
        else
            return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);

    }
    
    int getDepth(TreeNode* pRoot){
        if (pRoot == NULL) return 0;
        return max(getDepth(pRoot->left) + 1, getDepth(pRoot->right) + 1);
    }
};
           

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

class Solution {
public:
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
        int len = data.size();
        if (len < 2) return;
        int one = 0;
        for (int i = 0;i < len; i++)
            one = one ^ data[i];
        int flag = 1;
        while (flag){
            if (one & flag) break;
            flag = flag << 1;
        }
        for (int i = 0; i < len; i++){
            if (flag& data[i])
                *num1 = *num1 ^ data[i];
            else
                *num2 = *num2^data[i];
        }
    }
};
           

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

class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {
        int l = 1, r = 1,sumx = 1;
        vector<vector<int>> ans;
        while (l<=r){
            r++;
            sumx+=r;
            while(sumx>sum){
                sumx -= l;
                l++;
            }
            if (sumx == sum && l != r){
                vector<int> tmp;
                for(int i = l;i <= r;i ++)  tmp.push_back(i);
                ans.push_back(tmp);
            }
        }
        return ans;
    }
};
           

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

class Solution {
public:
    vector<int> FindNumbersWithSum(vector<int> array,int sum) {
        vector<int> result;
        int len = array.size();
        if (len <= 1) return result;
        int Sum;
        int i = 0;
        int j = len - 1;
        while (i <j){
            Sum = array[i] + array[j];
            if (Sum > sum) j--;
            else if (Sum < sum) i++;
            else{
                result.push_back(array[i]);
                result.push_back(array[j]);
                break;
            }
        }
        return result;
    }
};
           

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

class Solution {
public:
    string LeftRotateString(string str, int n) {
        string str1;
        str1 = str.substr(0,n);
        str.erase(0,n);
        return (str+str1);
    }
};
           

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

class Solution {
public:
    string ReverseSentence(string str) {
        int len = str.size();
        int start = 0;
        for (int i = 0; i <len; i++){
            if (str[i] == ' '){
                reverse(str.begin()+start,str.begin()+i);
                start = i + 1;
            }
            if (i == len - 1){
                reverse(str.begin()+start,str.end());
            }
        }
        reverse(str.begin(), str.end());
        return str;
    }
};
           

45.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.empty()) return false;
        int len = numbers.size();
        int max = -1;
        int min = 14;
        int count[14] = {0};
        for (int i = 0;i<len;i++){
            count[numbers[i]]++;
            if (numbers[i] == 0) continue;
            if (count[numbers[i]] > 1) return false;
            if(numbers[i]>max)max = numbers[i];
            if(numbers[i]<min)min = numbers[i];
        }
        if(max-min<5)return true;
        return 0;
        
    }
};
           

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

class Solution {
public:
    int LastRemaining_Solution(int n, int m)
    {
        //f(n,m)={f(n-1,m)+m}%n。
        if(n==0)return -1;
        int s=0;
        for(int i = 2;i<=n;i++){
            s =(s+m)%i;
        }
        return s;
    }
};
           

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

class Solution {
public:
    int Sum_Solution(int n) {
        int res = n;
        res&&(res+=Sum_Solution(n-1));
        return res;
    }
};
           

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

/*
首先看十进制是如何做的: 5+7=12,三步走
第一步:相加各位的值,不算进位,得到2。
第二步:计算进位值,得到10. 如果这一步的进位值为0,那么第一步得到的值就是最终结果。
第三步:重复上述两步,只是相加的值变成上述两步的得到的结果2和10,得到12。
同样我们可以用三步走的方式计算二进制值相加: 5-101,7-111 第一步:相加各位的值,不算进位,
得到010,二进制每位相加就相当于各位做异或操作,101^111。
第二步:计算进位值,得到1010,相当于各位做与操作得到101,再向左移一位得到1010,(101&111)<<1。
第三步重复上述两步, 各位相加 010^1010=1000,进位值为100=(010&1010)<<1。
继续重复上述两步:1000^100 = 1100,进位值为0,跳出循环,1100为最终结果 */
class Solution {
public:
    int Add(int num1, int num2)
    { 
      return num2 ? Add(num1^num2, (num1&num2)<<1) : num1;
    }
};
           

49.将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

class Solution {
public:
    int StrToInt(string str) {
        int len = str.length();
        int s;
        int result=0;
        if (len<=0) return 0;
        if(str[0]=='-')
            s = -1;
        else
            s = 1;
        for (int i = (str[i]=='-' || str[i]=='+')?1:0;i<len;i++){
            if (!(str[i]>='0' && str[i]<='9')) return 0;
            result = result*10+str[i]-'0';
        }
        return result * s;
    }
};
           

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

51.给定一个数组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]。不能使用除法。

class Solution {
public:
    vector<int> multiply(const vector<int>& A) {
        vector<int> B;
        int length = A.size();
        for (int i = 0;i<length;i++){
            int number = 1;
            for (int j = 0;j<length;j++){
                if (j == i) continue;
                number *= A[j];
                
            }
            B.push_back(number);
        }
        return B;
    
    }
};
           

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

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if(str[0]=='\0' && pattern[0]=='\0')
            return true;
        if(str[0]!='\0' && pattern[0]=='\0')
            return false;
        if(pattern[1]=='*'){
            if(pattern[0]==str[0]||(pattern[0]=='.'&&str[0]!='\0'))
                return match(str+1,pattern) || match(str,pattern+2);
            else
                return match(str,pattern+2);
        }
        if(str[0]==pattern[0]||(pattern[0]=='.'&& str[0]!='\0'))
            return match(str+1,pattern+1);
        return false;
    }
};
           

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

//注意表示数值的字符串遵循的规则;
//在数值之前可能有一个“+”或“-”,接下来是0到9的数位表示数值的整数部分,如果数值是一个小数,那么小数点后面可能会有若干个0到9的数位
//表示数值的小数部分。如果用科学计数法表示,接下来是一个‘e’或者‘E’,以及紧跟着一个整数(可以有正负号)表示指数。
class Solution {
public:
    bool isNumeric(char* string)
    {
        if(string==NULL or *string=='\0')
            return false;
        if(*string=='+'||*string=='-')
            string++;
        int dot=0,num=0,nume=0;
        while(*string != '\0'){
            if(*string>='0' && *string<='9'){
                string++;
                num =1;
            }
            else if(*string=='.'){
                if(dot>0||nume>0)
                    return false;
                string++;
                dot = 1;
            }
            else if(*string=='e' || *string=='E'){
                if(nume>0||num==0)
                    return false;
                string++;
                nume++;
                if(*string=='+' || *string=='-')
                    string++;
                if(*string=='\0')
                    return false;
            }
            else
                return false;
        }
        return true;
    }
};
           

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

class Solution
{
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
         ++hashArray[ch-'\0'];
        if( hashArray[ch-'\0'] == 1){
            data.push_back(ch);
        }
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        while( !data.empty() && hashArray[data.front()] >= 2 ){
            data.pop_front();
        }
        if( data.empty() )
            return '#';
        return data.front();
    }
 
    private:
    unsigned char hashArray[128];
    deque<char> data;
};
           

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
    {
         if(pHead==NULL)return NULL;
         //先计算环中结点的个数
         //快慢指针相遇结点一定在环中
         ListNode *pFast=pHead,*pSlow=pHead->next;
         while(pFast!=NULL&&pSlow!=NULL&&pFast!=pSlow){
            pSlow=pSlow->next;
            pFast=pFast->next;
            if(pFast!=NULL)
                pFast=pFast->next;
         }
         //开始统计环结点数
         int countNum=1;
         ListNode *pTempNode=pFast->next;
         if(pFast==pSlow&&pFast!=NULL){
             while(pTempNode!=pFast){
                 pTempNode=pTempNode->next;
                 ++countNum;
             }
         }
         else
             return NULL;
         //再设两指针,一先一后
         ListNode *pNode1=pHead,*pNode2=pHead;
         for(int i=0;i<countNum;i++){
                pNode1=pNode1->next;
         }
         while(pNode1!=pNode2){
             pNode1=pNode1->next;
             pNode2=pNode2->next;
         }
         return pNode1;
          
    }
};
           

56.在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表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){
            return nullptr;
        }
        ListNode* ret=pHead;
        ListNode* pre=nullptr,*current=pHead;
        while (current) {
            bool shoud_delete=false;
            if(current->next&&current->val==current->next->val){
                shoud_delete=true;
            }
            if(!shoud_delete){
                pre=current;
                current=current->next;
            }else{
                int val=current->val;
                ListNode* pnext;
                while (current&&(current->val==val)) {
                    pnext=current->next;
                    delete current;
                    current=pnext;
                }
                if(pre==nullptr){
                    pHead=current;
                }else{
                    pre->next=current;
                }
                 
            }
        }
        return pHead;
    }
};
           

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

/*
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;
        }
        TreeLinkNode* next = nullptr;
        //先右子节点的左子节点遍历
        if(pNode->right != nullptr){
            TreeLinkNode* rightNode  = pNode->right;
            while(rightNode->left != nullptr){
                rightNode = rightNode->left;
            }
            next = rightNode;
        }
            //向父结点遍历
        else if(pNode->next != nullptr){
            TreeLinkNode* parentNode = pNode->next;
            TreeLinkNode* currentNode = pNode;
            while(parentNode != nullptr  && currentNode == parentNode->right){
                currentNode = parentNode;
                parentNode = parentNode->next;
            }
            next = parentNode;
        }
        return next;
    }
};
           

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

/*
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)
    {
        return isSymmetrical(pRoot,pRoot);
    }
    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);
    }
 
};
           

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

/*
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) {
        vector<vector<int> > res;
        if(pRoot==NULL) return res;
        queue<TreeNode*> que;
        que.push(pRoot);
        bool even=false;
        while(!que.empty()){
            vector<int> vec;
            int size=que.size();
            for(int i=0;i<size;i++){
                 TreeNode* temp=que.front();
                que.pop();
                vec.push_back(temp->val);
                if(temp->left!=NULL) que.push(temp->left);
                if(temp->right!=NULL) que.push(temp->right);
            }
            if(even)
                std::reverse(vec.begin(),vec.end());
              res.push_back(vec);
            even=!even;
             
        }
        return res;
    }
     
};
           

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

/*
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) {
            vector<vector<int> > vv;
            vector<int> ve;
            queue<TreeNode*> que;
            queue<int> dque;
            int depth=0;
            que.push(pRoot);
            dque.push(depth);
            TreeNode *node;
            while(!que.empty()){
                node=que.front();
                if(depth!=dque.front()){
                    vv.push_back(ve);
                    ve.clear();
                    depth=dque.front();
                }
                que.pop();
                dque.pop();
                if(node){
                    que.push(node->left);
                    que.push(node->right);
                    dque.push(depth+1);
                    dque.push(depth+1);
                    ve.push_back(node->val);
                }
            }
            return vv;
        }
     
};
           

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

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<int> buf;
    void dfs1(TreeNode *root) {
        if(!root) buf.push_back(0xFFFFFFFF);
        else {
            buf.push_back(root->val);
            dfs1(root->left);
            dfs1(root->right);
        }
    }
    TreeNode* dfs2(int* &p) {
        if(*p==0xFFFFFFFF) {
            p++;
            return NULL;
        }
        TreeNode* res=new TreeNode(*p);
        p++;
        res->left=dfs2(p);
        res->right=dfs2(p);
        return res;
    }
    char* Serialize(TreeNode *root) {
        buf.clear();
        dfs1(root);
        int bufSize=buf.size();
        int *res=new int[bufSize];
        for(int i=0;i<bufSize;i++) res[i]=buf[i];
        return (char*)res;
    }
    TreeNode* Deserialize(char *str) {
        int *p=(int*)str;
        return dfs2(p);
    }
};
           

62.给定一棵二叉搜索树,请找出其中的第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:
    void inorder(TreeNode* root,TreeNode* &ans){
        if(root){
            inorder(root->left,ans);
            count--;
            if(!count) ans = root;
            inorder(root->right,ans);
        }
    }
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(!pRoot || k < 1) return nullptr;
        TreeNode* ans = NULL;
        count = k;
        inorder(pRoot,ans);
        return ans;
    }
private:
    int count;
     
};
           

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

class Solution {
public:
    void Insert(int num)
    {
        if(((max.size()+min.size())&1)==0)
        {
            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>());
        }
        else
        {
            if(min.size()>0&&num>min[0])
            {
                min.push_back(num);
                push_heap(min.begin(),min.end(),greater<int>());
                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>());
        }
    }
 
    double GetMedian()
    {
        if((max.size()+min.size())<=0)
            return 0.0;
        else{
            if(((max.size()+min.size())&1)==0)
            {
               return (max[0]+min[0])/2.0;
            }
            else
            {
                return (double)min[0];
            }
        }
    }
    vector<int> max;
    vector<int> min;
};
           

64.给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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)
    {
        vector<int>max;
        if(num.empty()||size>num.size()||size<1)
            return max;
        int m;
        for(int i=0;i<num.size()-size+1;i++)
            {
            m=num[i];
            for(int j=i+1;j<i+size;j++)
            {
             
            if(num[j]>m)
                {
                m=num[j];
            } 
         }
            max.push_back(m);
        }
             
       return max;    
    }
};
           

65.请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str,int now,vector<bool> &IsIn){
        if(*str!=matrix[now])
            return false;
        if(str[1]=='\0')
            return true;
        IsIn[now]=1;
        if(now%cols>0&&IsIn[now-1]==0&&hasPath(matrix,rows,cols,str+1,now-1,IsIn))
            return true;
        if(now%cols<cols-1&&IsIn[now+1]==0&&hasPath(matrix,rows,cols,str+1,now+1,IsIn))
            return true;
        if(now/cols>0&&IsIn[now-cols]==0&&hasPath(matrix,rows,cols,str+1,now-cols,IsIn))
            return true;
        if(now/cols<rows-1&&IsIn[now+cols]==0&&hasPath(matrix,rows,cols,str+1,now+cols,IsIn))
            return true;
        IsIn[now]=0;
        return false;
    }
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if(matrix==NULL||str==NULL||rows<=0||cols<=0)
            return false;
        if(*str=='\0')
            return true;
        vector<bool> IsIn(rows*cols,0);
        int i=0;
        while(i<rows*cols&&matrix[i]!='\0'){
            if(hasPath(matrix,rows,cols,str,i,IsIn))
                return true;
            i++;
        }
        return false;
    }
 
};
           

66.地上有一个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 get_sum(int num)
        {
        int sum=0;
        while(num)
            {
            sum+=num%10;
            num=num/10;
        }
        return sum;
    }
    bool check(int col,int row,int k)
        {
       return get_sum(col)+get_sum(row)<=k;
             
         
    }
    int compute(int i,int j,bool* a,int rows,int cols,int k)
        {
        int cnt=0;
        if(check(i,j,k)&&i>=0&&i<rows&&j>=0&&j<cols&&!a[i*cols+j])
    {
            a[i*cols+j]=true;
             cnt=1+compute(i-1,j,a,rows,cols,k)+compute(i+1,j,a,rows,cols,k)
                 +compute(i,j-1,a,rows,cols,k)+compute(i,j+1,a,rows,cols,k);
        }
            
            return cnt;
    }
    int movingCount(int threshold, int rows, int cols)
    {
        bool a[rows*cols];
        for(int i=0;i<rows*cols;++i)
            a[i]=false;
        int cnt=compute(0,0,a,rows,cols,threshold);
        return cnt;
         
    }
};