为什么这个 java 代码比 cpp 花费更少的 space 和时间
why this java code takes less space and time compared to cpp
class Solution {
public:
void inorder(TreeNode* root, int low, int high, int& res){
if(root != nullptr){
inorder(root->left, low, high, res);
if(root->val <= high && root->val >= low){
res += root->val;
}
inorder(root->right, low, high, res);
}
}
int rangeSumBST(TreeNode* root, int low, int high) {
int res=0;
inorder(root, low, high, res);
return res;
}
};
Java:
class Solution {
int res;
public void inorder(TreeNode root, int low, int high){
if(root != null){
inorder(root.left, low, high);
if(root.val <= high && root.val >= low){
res += root.val;
}
inorder(root.right, low, high);
}
}
public int rangeSumBST(TreeNode root, int low, int high) {
res = 0;
inorder(root, low, high);
return res;
}
}
Leetcode第938题,求BST的Range和[low, high]
我在两种语言上做的几乎一样(我猜我是 java 的新手),但是 java 代码与 cpp 相比为什么这么快是不是与指针有关和参考或网站使用的编译器?
问候
经过一番研究,我发现它与平台本身有关。 Leetcode: Is java faster than C++
根据一条评论,“他们从 Java 的基准测试中删除了编译和其他过程运行时。
这意味着对于 C/C++ 解决方案,编译时间计入运行时
不确定这有多可靠。
class Solution {
public:
void inorder(TreeNode* root, int low, int high, int& res){
if(root != nullptr){
inorder(root->left, low, high, res);
if(root->val <= high && root->val >= low){
res += root->val;
}
inorder(root->right, low, high, res);
}
}
int rangeSumBST(TreeNode* root, int low, int high) {
int res=0;
inorder(root, low, high, res);
return res;
}
};
Java:
class Solution {
int res;
public void inorder(TreeNode root, int low, int high){
if(root != null){
inorder(root.left, low, high);
if(root.val <= high && root.val >= low){
res += root.val;
}
inorder(root.right, low, high);
}
}
public int rangeSumBST(TreeNode root, int low, int high) {
res = 0;
inorder(root, low, high);
return res;
}
}
Leetcode第938题,求BST的Range和[low, high]
我在两种语言上做的几乎一样(我猜我是 java 的新手),但是 java 代码与 cpp 相比为什么这么快是不是与指针有关和参考或网站使用的编译器?
问候
经过一番研究,我发现它与平台本身有关。 Leetcode: Is java faster than C++
根据一条评论,“他们从 Java 的基准测试中删除了编译和其他过程运行时。
这意味着对于 C/C++ 解决方案,编译时间计入运行时
不确定这有多可靠。