leetcode随笔II

  1. leetcode几道简单题目
    1. 1知识点
    1. 2.方法
  2. 总结
    一.leetcode几道简单题目
    1.Single Number给定一个数组,仅有一个数字只出现一次,其他均出现两次
    知识点:二进制或操作
    方法:①所有数字依次进行或操作②返回最后的结果值
    扩展:Single Number II有两个数字出现仅出现依次,其他数字都出现两次
    tips:所有数字进行或操作,依据二进制位最右侧最低位为1,分成两组,每组当中出现一次的数字仅有一个转到求解Single Number的问题。
    2.First Bad Version找到第一个不合格的产品,从第一个产品不合格后,以后所有的产品均不合格
    知识点:二分查找;顺序查找
    方法:二分查找
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
/*
class Solution {//方法超时
public:
    int firstBadVersion(int n) 
    {
        for(int i=0;i<=n;)
        {
            if(!isBadVersion(i))
                i++;
            else
                return i;
        }
    }
};*/
class Solution {//应用二分查找思路
public:
    int firstBadVersion(int n) 
    {
        int low=1;
        int high=n;
        while(low<high)
        {
            int mid=low+(high-low)/2;
            if(isBadVersion(mid))
                high=mid;
            else
                low=mid+1;
        }
        return high;
    }
};

3.Binary Tree Paths打印二叉树的路径
知识点:二叉树的深度优先遍历
方法:应用递归深度优先遍历二叉树
扩展: leetcode pathsum tree link:二叉树路径和问题
参考代码如下:(代码因打印路径要求带有箭头稍微复杂)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void binaryTreePathsHelper(TreeNode* root, string& s, vector<string>& result)
    {
        if(root==NULL)
            return;
        int length = s.length();
        string temp1, temp2;
        temp1 = s;
        if(length>0)
            s = s+"->";
        s = s + to_string(root->val);
        if(root->left == NULL && root->right==NULL)
            result.push_back(s);
        temp2 = s;
        binaryTreePathsHelper(root->left, s, result);
        s = temp2;
        binaryTreePathsHelper(root->right, s, result);
        s = temp1;
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        string s;
        vector<string> result;
        binaryTreePathsHelper(root, s, result);
        return result;
    }
};

以下为python 代码,join很好的避开了这个麻烦

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        if not root:
            return []
        stack,res=[(root,[str(root.val)])],[]
        while stack:
            temp,path=stack.pop()#现在的path只是保存了相关的路径
            if not temp.left and not temp.right:
                res+=[('->'.join(path))]#这里用箭头每一个路径连接起来
            if temp.left:
                stack.append((temp.left,path+[str(temp.left.val)]))
            if temp.right:
                stack.append((temp.right,path+[str(temp.right.val)]))
        return res

4.Rotate Array数组旋转Rotate an array of n elements to the right by k steps.For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
知识点:二分查找(交换);字符串旋转
方法:①将字符串分成两部分(n-k,k)②每部分进行局部交换③整体交换。
代码如下:

class Solution {
public:
/*    void rotate(vector<int>& nums, int k) //方法超时
    {

        if(nums.size()==1)
         return ;
        if (k > nums.size())
            k = k%nums.size();
        for(int i=0;i<k;i++)
        {
            int temp;
            temp=nums[nums.size()-1];
            for(int j=nums.size()-1;j>0;j--)
            {
                nums[j]=nums[j-1];
            }
            nums[0]=temp;
        }
    }
*/
     void rotate(vector<int>& nums, int k)
     {
         if(k>nums.size())
            k=k%nums.size();
         if(k==0)
            return ;
         if(nums.size()==0||nums.size()==1)
            return ;
         reverse(nums,0,nums.size()-k-1);
         reverse(nums,nums.size()-k,nums.size()-1);
         reverse(nums,0,nums.size()-1);
     }
     void reverse(vector<int>&num,int start,int end)
     {
         int low=start,high=end;
         while(low<high)
         {
             int temp=num[low];
             num[low]=num[high];
             num[high]=temp;
             low++;
             high--;
         }
     }
};

5.String to Integer (atoi)字符串旋转
知识点:atoi API源码实现
方法:①查找第一个非空格字符②从左只有进行相应求和③非法字符返回前面有效字符的和④检查是否越界
tips: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.

代码如下:

class Solution {
public:
int myAtoi(string str) {
        long result = 0L;
        auto iter = str.begin();
        while(*iter == ' ')
            iter ++;

        bool isnegative = (*iter == '-')?true:false;
        if(*iter=='+' || *iter=='-')
            iter++;

        if(static_cast<int>(*iter) < '0' || static_cast<int>(*iter) > '9')
            return 0;
        int maxloop = 11;
        while (iter != str.end()
               &&(
                  static_cast<int>(*iter) >= static_cast<int>('0')
                  &&static_cast<int>(*iter) <= static_cast<int>('9')
                  )
               && maxloop > 0
               )
        {
            auto tmp = static_cast<int>(*iter - '0');
            result *= 10L;
            result += tmp;
            iter++;
            maxloop --;
        }

        if (maxloop == 0) {
            if(isnegative)
                return -2147483648;
            else
                return 2147483647;
        }

        if(isnegative)
        {
            result = -result;
            if( result < -2147483648L)
                result = -2147483648;
        }
        else if (result > 2147483647L)
            result = 2147483647;
        return static_cast<int>(result);

}
};

参考代码2:

//此代码不考虑越界问题
class Solution {
public:
    int myAtoi(string str)
    {
        double sum=0;
        int loc=0;
        for(loc=0;loc<str.size();loc++)
            if(str[loc]!=' ')
                break;
        if(loc==str.size())
            return 0;
        for(int i=str.size()-1,k=1;i>=loc;i--)
        {
            if(isDigit(str[i]))
            {
                sum+=((int)(str[i]-'0'))*k;
                k*=10;
            }
            else
            {
                if(i!=loc)
                {
                    sum=0;
                    k=1;
                }
            }

        }
            if(((int)(str[loc]-'-')==0))
               return (-sum);
            else
               return sum;

    }
    bool isDigit(char str)
    {
        int temp=(int)(str-'0');
        if(temp>9||temp<0)
            return false;
        else
            return true;
    }
};

二.总结
2.1①移位与&(与、或)等操作可以实现:乘除、辨分数字规律操作,计数操作②递归的深入,变量做函数的参数才能时刻保证其变化③字符串的旋转等操作,多关注整体与局部的关系2.2让我们一同努力,明天会更好!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值