醜數
把只包含質因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因爲它包含質因子7。 習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if (index <= 6) return index;
vector<int> res(index);
res[0]=1;
int t2=0,t3=0,t5=0;
for(int i=1;i<index;i++){
res[i]=min(res[t2]*2,min(res[t3]*3,res[t5]*5));
if(res[i]==res[t2]*2) t2++;
if(res[i]==res[t3]*3) t3++;
if(res[i]==res[t5]*5) t5++;
}
return res[index-1];
}
};
98. 驗證二叉搜索樹
難度中等523收藏分享切換爲英文關注反饋
給定一個二叉樹,判斷其是否是一個有效的二叉搜索樹。
假設一個二叉搜索樹具有如下特徵:
- 節點的左子樹只包含小於當前節點的數。
- 節點的右子樹只包含大於當前節點的數。
- 所有左子樹和右子樹自身必須也是二叉搜索樹。
示例 1:
輸入: 2 / \ 1 3 輸出: true
示例 2:
輸入: 5 / \ 1 4 / \ 3 6 輸出: false 解釋: 輸入爲: [5,1,4,null,null,3,6]。 根節點的值爲 5 ,但是其右子節點值爲 4 。
- 中序遍歷
- 遞歸
/**
* 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 isValidBST(TreeNode* root) {
if(root==NULL) return true;
stack<TreeNode*> st;
int tag=0,last=0;
while(!st.empty()||root){
while(root){
st.push(root);
root=root->left;
}
TreeNode *tmp=st.top();
st.pop();
if(tag==0){
last=tmp->val;
tag=1;
}else{
if(tmp->val<=last) return false;
else last=tmp->val;
}
if(tmp->right) root=tmp->right;
}
return true;
}
};
class Solution {
public:
bool helper(TreeNode *root,long long int lower,long long int upper ){
//考慮以root爲根的子樹,節點值是否在lower和upper之間
if(root==NULL) return true;
if(root->val<=lower || root->val>=upper) return false;
return helper(root->left,lower,root->val) && helper(root->right,root->val,upper);
}
bool isValidBST(TreeNode* root) {
return helper(root,LONG_MIN,LONG_MAX);
}
};