剑指offer刷题第二天

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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 pre,vector vin) {
        return reConstructSubBinaryTree(pre,vin,0,pre.size()-1,0,vin.size()-1);
    }
    TreeNode* reConstructSubBinaryTree(vector pre,vector vin,int preStart,int preEnd,int vinStart,int vinEnd){
        if(preStart <= preEnd){
            TreeNode *tempNode = new TreeNode(pre[preStart]);
            int i = vinStart;
            for(;i <= vinEnd;i++){
                if(vin[i] == pre[preStart]) break;
            }
            tempNode->left = reConstructSubBinaryTree(pre,vin,preStart+1,preStart+i-vinStart,vinStart,i-1);
            tempNode->right = reConstructSubBinaryTree(pre,vin,preEnd-vinEnd+i+1,preEnd,i+1,vinEnd);
            return tempNode;
        }else{
            return NULL;
        }
    }
};

题目描述

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

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

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

private:
    stack stack1;
    stack stack2;
};

题目描述

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

class Solution {
public:
    int minNumberInRotateArray(vector rotateArray) {
        int result = 0;
        if(!rotateArray.empty())
        {
            int start = 0;
            int end = rotateArray.size()-1;
            int mid = 0;
            while(start <= end){
                if(rotateArray[start] < rotateArray[end]){
                    result = rotateArray[start];
                    break;
                }
                mid = (start+end)/2;
                if(rotateArray[start] == rotateArray[mid] && rotateArray[mid] == rotateArray[end]){
                    result = rotateArray[mid];
                    for(int i = start+1; i < end; i++){
                        if(result > rotateArray[i]){
                            result = rotateArray[i];
                        }
                    }
                    return result;
                }else if(rotateArray[start] <= rotateArray[mid]){
                    start = mid+1;
                }else{
                    end = mid;
                }
            }
        }
        return result;
    }
};

你可能感兴趣的:(剑指offer刷题第二天)