leetcode隨筆雜談
leetcode9道簡單題目
1.Given an integer, write a function to determine if it is a power of two.
知識點:二進制的移位操作;能被2的n次冪數用二進制表示只有一個1
方法:
I.①將數字(n=1)與原數字進行與(&)操作②同時進行左移位(<<1),③求出1的出現的個數。
II.原數字&(原數字-1),如果爲2的倍數則結果爲0(方法很巧妙)
2.Given an integer, write a function to determine if it is a power of three.
知識點:數學對數換底公式;float的差值是1e-10,其並沒有精確值
方法:
將加上abs((int)(i+0.5)-i)進行強制int類型轉換,與i值作比較差值小於1e-10則在是其冪次方。(i=log3(n)其對數形式)
3.Happy number
知識點:hashTable應用(c++ set只存儲鍵值)
方法:
①將happy number的和存入set集合.②find set集合當中是否存在sum值(如果存在表明陷入到某個數的loop當中,說明不是happynumber;如果==1則返回true)
4.Ugly Number
知識點:數字找規律
方法:①判斷輸入值(n)是否能被num=2,3,5整除.②如果能,則updata n=n/num繼續判斷(終止條件爲n是否小於等於7)。
5.Implement Queue using Stacks
知識點:棧的基本概念及操作;隊列的基本概念及操作
方法:
I.一個棧作爲輔助存儲空間,並且始終保持爲空。
II.一個棧作爲入棧棧,另一個作爲出棧棧。
因此知識點很重要,所以代碼附到下面:
class Queue {
public:
// Push element x to the back of queue.
stack<int> stoSta1,stoSta2;
void push(int x)
{
if(stoSta2.empty())
stoSta1.push(x);
else
{
while(stoSta2.size()>0)
{
int temp=stoSta2.top();
stoSta1.push(temp);
stoSta2.pop();
}
stoSta1.push(x);
}
}
// Removes the element from in front of queue.
void pop(void)
{
if(stoSta2.size()>0)
{
stoSta2.pop();
}
else
{
while(stoSta1.size()>0)
{
int temp=stoSta1.top();
stoSta2.push(temp);
stoSta1.pop();
}
stoSta2.pop();
}
}
// Get the front element.
int peek(void)
{
if(stoSta2.size()>0)
{
return stoSta2.top();
}
else
{
while(stoSta1.size()>0)
{
int temp=stoSta1.top();
stoSta2.push(temp);
stoSta1.pop();
}
return stoSta2.top();
}
}
// Return whether the queue is empty.
bool empty(void)
{
if(stoSta1.size()==0&&stoSta2.size()==0)
return true;
else
return false;
}
};
思路補充:出棧操作保證一個棧爲空,入棧操作保證在隊1和對2當中交替進行
6.Balanced Binary Tree
知識點:平衡二叉樹的左右子樹均爲平橫二叉樹;二叉樹的深度
方法:
①遞歸求解二叉樹的深度②遞歸判斷二叉樹是否爲平橫二叉樹
代碼如下:
/**
* 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:
bool isBalanced(TreeNode* root)
{
if(!root)
{
return true;
}
int l=pathLengthHeight(root->left);
int r=pathLengthHeight(root->right);
if(l-r>1||r-l>1)
{
return false;
}
return isBalanced(root->left)&&isBalanced(root->right);
}
int pathLengthHeight(TreeNode*root)
{
if(!root)
{
return 0;
}
int max1=pathLengthHeight(root->left)+1;
int max2=pathLengthHeight(root->right)+1;
return (max1>max2)?max1:max2;
}
};
python 代碼:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
if abs(self.depth(root.left)-self.depth(root.right))<=1:
return self.isBalanced(root.left) and self.isBalanced(root.right)
else:
return False
def depth(self,root):
if not root:
return 0
if root and not root.left and not root.right:
return 1
return max(self.depth(root.left)+1,self.depth(root.right)+1)
7.Lowest Common Ancestor of a Binary Search Tree
知識點:二叉排序樹的中序便利是有序數組;二叉排序樹最低公共祖先的範圍[min,max]之間
方法:遞歸判斷二叉樹的值是否在[min,max]之間
代碼如下:
/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
int max;
int min;
if(p->val>q->val)
{
max=p->val;
min=q->val;
}
else
{
max=q->val;
min=p->val;
}
if(root->val<=max&&root->val>=min)
{
return root;
}
if(root->val<min)
{
return lowestCommonAncestor(root->right,p,q);
}
if(root->val>max)
{
return lowestCommonAncestor(root->left,p,q);
}
}
};
python 代碼:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if(p.val>q.val):
temp=p
p=q
q=temp
if root.val>q.val:
return self.lowestCommonAncestor(root.left,p,q)
if root.val<p.val:
return self.lowestCommonAncestor(root.right,p,q)
return root
8.Climbing Stairs
知識點:動態規劃(以後集中講解);數學找遞歸公式;遞歸與非遞歸的轉換
方法:
①第一次爬一個階梯則下面有f(n-1)種爬法; ②第一次爬兩個階梯則下面有f(n-2)中爬法③遞推規律爲:f(n)=f(n-1)+f(n-2);
代碼如下:
class Solution {
public:
int climbStairs(int n)
{
/* if(n==1)
{
return 1;
}
if(n==2)
{
return 2;
}
return climbStairs(n-1)+climbStairs(n-2);
}
*/
vector<int> sta;
sta.push_back(1);
sta.push_back(2);
for(int i=2;i<n;i++)
{
int temp=sta[i-1]+sta[i-2];
sta.push_back(temp);
}
return sta[n-1];
}
};
9.Roman to Integer
知識點:數學找Roman的規律;HashTable的應用
方法:
①將Roman數字表示的十進制數用HashTable存儲(c++ map)②從右向左依次比較Roman數字的十進制值(小則加,大則減)③求出總體的和
代碼如下:
class Solution {
public:
int romanToInt(string s)
{
map<char,int> hashTable;
hashTable.insert(make_pair('I',1));
hashTable.insert(make_pair('V',5));
hashTable.insert(make_pair('X',10));
hashTable.insert(make_pair('L',50));
hashTable.insert(make_pair('C',100));
hashTable.insert(make_pair('D',500));
hashTable.insert(make_pair('M',1000));
int sum = hashTable.find(s[s.size() - 1])->second;
for (int i = s.size() - 1; i > 0; i--)
{
if (hashTable.find(s[i])->second <= hashTable.find(s[i - 1])->second)
{
sum += hashTable.find(s[i - 1])->second;
}
else
{
sum -= hashTable.find(s[i - 1])->second;
}
}
return sum;
}
};
總結
綜上,I.我們需要不斷儲備基礎知識:①找數字當中存在的規律②熟悉基本數據結構概念③掌握組成原理裏面移位等操作;II.讓我們我們一同努力,明天會更好!