每日一题计划
LeetCode难度三个等级:
2019-06-10
Easy
水题,就是求字符串\(S\)中有多少字母在字符串\(J\)中,字符串\(J\)中的字母各不相同。
代码如下:复杂度\(O(S.length+J.length)\)。
class Solution {
public:
int numJewelsInStones(string J, string S) {
int sum=0;
unordered_set<char>se(J.begin(),J.end());
for(auto i : S) sum+=se.count(i);
return sum;
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Jewels and Stones.
Memory Usage: 8.6 MB, less than 56.84% of C++ online submissions for Jewels and Stones.
2019-06-11
Easy
题意就是题目的名字,给你一个建好的二叉搜索树(\(BST\))的根节点\(root\),让你计算值位于\(L\)和\(R\)之间节点的值的和。
\[ans=\sum\{node.value\ which\ L\le node.value\le R\}
\]
然后代码就是一个简单的后序遍历加类似于二分的剪枝。
/**
* 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:
int rangeSumBST(TreeNode* root, int L, int R) {
int sum=0;
if(root){
if(root->val>=L) sum+=rangeSumBST(root->left,L,R);
if(root->val<=R) {
sum+=rangeSumBST(root->right,L,R);
if(root->val>=L) sum+=root->val;
}
}
return sum;
}
};
Runtime: 144 ms, faster than 90.39% of C++ online submissions for Range Sum of BST.
Memory Usage: 41.3 MB, less than 41.58% of C++ online submissions for Range Sum of BST.