首页 > 解决方案 > 为什么这个java代码比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;
    }
};

爪哇:

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 题

Leetcode 第 938 题 问题是求 BST [low, high] 的 Range sum

我在两种语言中都做的几乎一样(我猜,但我是 java 新手),但是 java 代码与 cpp 相比如何如此之快,它与指针和引用或站点使用的编译器有关吗?
问候

标签: javac++memoryruntime

解决方案


经过一番研究,我发现它与平台本身有关。Leetcode:java 比 C++ 快吗

根据一条评论“他们从 Java 的基准测试中删除了编译和其他过程运行时。这意味着对于 C/C++ 解决方案,编译时间计入运行时”
不确定这有多可靠。


推荐阅读