剑指offer

1)二维数组中的查找
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        if(array.size() <= 0)
            return false;
        int rows = array.size();
        int cols = array[0].size();
        int i = 0, j = cols-1;
        while(i < rows && j >= 0)
        {
            if(array[i][j] == target)
                return true;
            else if(array[i][j] > target)
                j--;
            else
                i++;
        }
        return false;
    }
};

2)替换空格
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
    void replaceSpace(char *str,int length) {
        if(str == NULL || length <= 0)
            return ;
        int count = 0;
        for(int i=0; i<strlen(str); i++)
        {
            if(str[i] == ' ')
                count++;
        }
        int newLength = strlen(str) + count * 2 + 1;
        if(newLength > length)
            return ;
        int i = strlen(str) + 1;
        int j = newLength;
        while(i >= 0 && j > i)
        {
            if(str[i] == ' ')
            {
                str[j--] = '0';
                str[j--] = '2';
                str[j--] = '%';
            }
            else
                str[j--] = str[i];
            i--;
        }
    }
};

3)从尾到头打印链表
输入一个链表,从尾到头打印链表每个节点的值
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> res;
    vector<int> printListFromTailToHead(ListNode* head) {
        if(head == NULL)
            return res;
        if(head->next)
            res = printListFromTailToHead(head->next);
        res.push_back(head->val);
        return res;
    }
};

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 || vin.size() == 0)
            return NULL;
        return constructTree(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
    }
    TreeNode* constructTree(const vector<int>& pre, int s1, int e1, const vector<int>& vin, int s2, int e2)
    {
        int i;
        for(i=s2; i<=e2; i++)
        {
            if(vin[i] == pre[s1])
                break;
        }
        if(i > e2)
            return NULL;
        TreeNode* head = new TreeNode(pre[s1]);
        head->left = constructTree(pre, s1+1, s1+i-s2, vin, s2, i-1);
        head->right = constructTree(pre, s1+i-s2+1, e1, vin, i+1, e2);
        return head;
    }
};

5)两个栈实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if(stack2.empty())
        {
            while(!stack1.empty())
            {
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        int res = -1;
        if(!stack2.empty())
        {
            res = stack2.top();
            stack2.pop();
        }
        return res;
    }

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 i = 0, j= rotateArray.size()-1;
        int mid = i;
        while(rotateArray[i] >= rotateArray[j])
        {
            if(j -  i == 1)
            {
                mid = j;
                break;
            }
           
            mid = (i + j) / 2;
            if(rotateArray[i] == rotateArray[mid] && rotateArray[mid] == rotateArray[j])
                return midNumber(rotateArray, i, j);
            if(rotateArray[mid] >= rotateArray[i])
                i = mid;
            else if(rotateArray[mid] <= rotateArray[j])
                j = mid;
            
        }
        return rotateArray[mid];
    }
    int midNumber(const vector<int>& rotateArray, int start, int end)
    {
        int min = rotateArray[start];
        for(int i=start+1; i<=end; i++)
            if(rotateArray[i] < min)
                min = rotateArray[i];
        return min;
    }
};

7)斐波那契数列
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39
class Solution {
public:
    int Fibonacci(int n) {
        if(n < 2)
            return n;
        int a = 0, b = 1;
        int c = 0;
        for(int i=2; i<=n; i++)
        {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
};

8)跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
class Solution {
public:
    int jumpFloor(int number) {
        if(number == 1)
            return 1;
        else if(number == 2)
            return 2;
        int a = 1, b = 2, c;
        for(int i=3; i<=number; i++)
        {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
};

9)变态跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
class Solution {
public:
    int jumpFloorII(int number) {  // f(n) = 2^(n-1)
        return 1 << (number -1);
    }
};

10)矩形覆盖
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
解析:用第一个1×2小矩形去覆盖大矩形的最左边时有两个选择,竖着放和横着放,当竖着放时右边还剩下2×(n-1)的区域,这种情况下的覆盖方法记为f(n-1)
当横着放在左上角的时候,左下角必须横着放一个1×2的小矩形,而右边还剩下2×6的区域,这种情况下的覆盖方法记为f(n-2).
class Solution {
public:
    int rectCover(int number) {
        if(number <= 2)
            return number;
        int a = 1, b = 2;
        int c;
        for(int i=3; i<=number; i++)
        {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
};

11)二进制中1的个数
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示
class Solution {
public:
     int  NumberOf1(int n) {
         int res = 0;
         while(n)
         {
             res++;
             n = n & (n-1);
         }
         return res;
     }
};

12)数值的整数次方
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
class Solution {
public:
    double Power(double base, int exponent) {
        if(equal(base, 0.0) && exponent < 0)
            return 0.0;
        unsigned int absExponent = abs(exponent);
        double result = PowerWithUnsignedExponent(base, absExponent);
        if(exponent < 0)
            result = 1.0 / result;
        return result;
    }
    bool equal(double num1, double num2)
    {
        if(num1 - num2 < 0.0000001 && num1 - num2 > -0.0000001)
            return true;
        return false;
    }
    
    double PowerWithUnsignedExponent(double base, unsigned int exponent)
    {
        if(exponent == 0)
            return 1;
        else if(exponent == 1)
            return base;
        double result = PowerWithUnsignedExponent(base, exponent>>1);
        result *= result;
        if(exponent & 0x1 == 1)
            result *= base;
        return result;
    }
};

13)调整数组顺序使奇数位于偶数前面
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
class Solution {
public:
    void reOrderArray(vector<int> &array) {
        int n = array.size();
        if(n <= 1)
            return ;
        vector<int> tmp(n);
        int oddCount = 0;
        for(int i=0; i<n; i++)
        {
            if(array[i] & 0x1)
            {
                tmp[oddCount] = array[i];
                oddCount++;
            }
               
        }
        for(int i=0; i<n; i++)
        {
            if((array[i] & 0x1) == 0)   // & 的优先级小于 ==
                tmp[oddCount++] = array[i];
        }
        array = tmp;
    }
};

14)链表中倒数第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 == NULL || k == 0)
            return NULL;
        ListNode* pFast = pListHead;
        ListNode* pSlow = pListHead;
        for(unsigned int i=0; i<k-1; i++)
        {
            if(pFast->next == NULL)
                return NULL;
            pFast = pFast->next;
        }
        while(pFast->next != NULL)
        {
            pSlow = pSlow->next;
            pFast = pFast->next;
        }
        return pSlow;
    }
};

15) 反转链表
输入一个链表,反转链表后,输出链表的所有元素。
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* pre = NULL;
        ListNode* p = pHead;
        ListNode* pn = NULL;
        while(p)
        {
            pn = p->next;
            p->next = pre;
            pre = p;
            p = pn;
        }
        return pre;
    }
};

16)合并两个排序的列表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
/*
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 == NULL)
            return pHead2;
        else if(pHead2 == NULL)
            return pHead1;
        ListNode* newHead = NULL;
        if(pHead1->val < pHead2->val)
        {
            newHead = pHead1;
            newHead->next = Merge(pHead1->next, pHead2);
        }
        else
        {
            newHead = pHead2;
            newHead->next = Merge(pHead1, pHead2->next);
        }
            
        return newHead;
    }
};

17)树的子结构
输入两棵二叉树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 == NULL || pRoot2 == NULL)
            return false;
        bool res = false;
        if(pRoot1->val == pRoot2->val)
            res = IsSubtree(pRoot1, pRoot2);
        if(!res)
            res = HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2);
        return res;
    }
    
    bool IsSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if(pRoot2 == NULL)
            return true;
        if(pRoot1 == NULL)
            return false;
        if(pRoot1->val != pRoot2->val)
            return false;
        return IsSubtree(pRoot1->left, pRoot2->left) && IsSubtree(pRoot1->right, pRoot2->right);
    }
}; 

18)二叉树的镜像
操作给定的二叉树,将其变换为源二叉树的镜像。
/*
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;
        if(pRoot->left)
            Mirror(pRoot->left);
        if(pRoot->right)
            Mirror(pRoot->right);
    }
};

19)顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: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) {
        vector<int> res;
        int rows = matrix.size();
        int cols = matrix[0].size();
        if(rows == 0 || cols == 0)
            return res;
        int left = 0, top = 0;
        int right = cols-1, bottom = rows-1;
        while(top <= bottom && left <= right)
        {
            int i, j;
            for(j=left; j<=right; j++)
                res.push_back(matrix[top][j]);
                for(i=top+1; i<=bottom; i++)
                res.push_back(matrix[i][right]);
            if(top < bottom)
            {
                for(j=right-1; j>left; j--)
                          res.push_back(matrix[bottom][j]);
            }
        
            if(left < right)
            {
                   for(i=bottom; i>top; i--)
                      res.push_back(matrix[i][left]);
            }
            top++;
            left++;
            right--;
            bottom--;
        }
        return res;
    }
};

20)包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
class Solution {
private:
    stack&
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值