编程之旅-Day35

目录

Day35-学习内容:

1.剑指Offer

面试题7:重建二叉树

面试题8:二叉树的下一个结点

 2.Leetcode

例1:atoi函数实现-字符串转整数

例2:股票买卖的最大利润


1.剑指Offer

面试题7:重建二叉树

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

思路:递归

考点:前序和中序遍历

代码:

class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        int vinlen=vin.size();
        if(vinlen==0){
            return NULL;
        }
        int rootval=pre[0];
        int p=0;
        for(p;p<vinlen;p++){
            if(vin[p]==rootval){
                break;
            }
        }
        vector<int> preleft,preright,vinleft,vinright;
        for(int i=0;i<vinlen;i++){
            if(i<p){
                vinleft.push_back(vin[i]);
                preleft.push_back(pre[i+1]);
            }
            else if(i>p){
                vinright.push_back(vin[i]);
                preright.push_back(pre[i]);
            }
        }
        TreeNode* root=new TreeNode(rootval);
        root->left=reConstructBinaryTree(preleft,vinleft);
        root->right=reConstructBinaryTree(preright,vinright);
        return root;
    }
};

面试题8:二叉树的下一个结点

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

思路:画图、举例

考点:中序遍历

代码:

class Solution {
public:
    TreeLinkNode* GetNext(TreeLinkNode* pNode)
    {
        if(pNode==nullptr){
            return nullptr;
        }
        TreeLinkNode* pNext=nullptr;
        if(pNode->right!=nullptr){
            TreeLinkNode* pRight=pNode->right;
            while(pRight->left!=nullptr){
                pRight=pRight->left;
            }
            pNext=pRight;
        }
        else if(pNode->next!=nullptr){
            TreeLinkNode* pCurrent=pNode;
            TreeLinkNode* pParent=pNode->next;
            while(pParent!=nullptr&&pCurrent==pParent->right){
                pCurrent=pParent;
                pParent=pParent->next;
            }
            pNext=pParent;           
        }
        return pNext;
    }
};

 2.Leetcode

例1:atoi函数实现-字符串转整数

题目描述:

Implement atoi to convert a string to an integer. 

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. 

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. 

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. 

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. 

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. 

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

思路:考虑多种特殊情况(1.去掉前面若干空字符 2.开头正负号 3.整数溢出 4.非数字字符)

代码:

class Solution {
public:
    int atoi(const char *str) {  
        if(str==nullptr) return 0;
        long long res=0;
        int i=0;
        while(str[i]==' '){
            i++;
        }
        bool flag=false;
        if(str[i]=='+'){
            i++;
        }
        if(str[i]=='-'){
            i++;
            flag=true;
        }
        for(i;str[i]!='\0';i++){
            if(str[i]>='0'&&str[i]<='9'){
                res=res*10+str[i]-'0';
                if(res>INT_MAX){
                    return flag?INT_MIN:INT_MAX;
                }
            }
            else{
                return flag?-res:res;
            }
        }
        return flag?-res:res;
    }
};

解析:C语言itoa()函数和atoi()函数详解(整数转字符C实现

https://www.cnblogs.com/bluestorm/p/3168719.html

例2:股票买卖的最大利润

题目描述1:只进行一次交易

Say you have an array for which the i th element is the price of a given stock on day i

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. (注意本题要求最多只能完成一次交易)

思路:在最大价格前找一个最小价格,差值表示最大利润

代码:

牛客网通过,但leetcode不能通过!!

原因:没有对空指针进行判断

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int minprice=prices[0];
        int maxprofit=0;
        
        for(int i=0;i<prices.size();i++){
            if(prices[i]<minprice){
                minprice=prices[i];
            }
            maxprofit=max(maxprofit,prices[i]-minprice);
        }
        return maxprofit;
    }
};

leetcode通过代码:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int size=prices.size();
        if(size==0) return 0;   //一定要对空引用进行判断
        int minprice=prices[0];
        int maxprofit=0;
        
        for(int i=1;i<size;i++){
            if(prices[i]<minprice){
                minprice=prices[i];
            }
            maxprofit=max(maxprofit,prices[i]-minprice);
        }
        return maxprofit;
    }
};

题目描述2:可多次买卖一支股票

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

分析:

复杂度分析

  • 时间复杂度:O(n)O(n)。遍历一次。

  • 空间复杂度:O(1)O(1)。需要常量的空间。

代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int size=prices.size();
        if(size==0) return 0;
        int max=0;
        for(int i=1; i<size; i++){
            if(prices[i]>prices[i-1]){
                max+=prices[i]-prices[i-1];
            }
        }
        return max;
    }
};

猜你喜欢

转载自blog.csdn.net/linyuhan3232/article/details/89445537