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讓我們一同努力,明天會更好!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章