簡體   English   中英

如何加快用Java編寫的遞歸方法

[英]How to speed up a recursive method written in Java

這是LeetCode的一個問題,我使用C ++解決了這個問題,但是當我將相同類型的方法與Java一起使用時,它會返回“超過時限”錯誤。 有人知道原因嗎?

這是問題所在:

將已排序的數組轉換為二進制搜索樹。 給定一個數組,其中元素按升序排序,請將其轉換為高度平衡的BST。

這是我用Java編寫的解決方案:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        if(num.length == 0) {
            return null;
        } else {
            return sub(num, 0, num.length-1);
        }
    }

    public TreeNode sub(int[] num, int start, int end) {
        int indexRoot = (start+end+1) / 2;
        TreeNode root = new TreeNode(num[indexRoot]);

        if(indexRoot > start) {
            root.left = sub(num, 0, indexRoot-1);
        }
        if(indexRoot < end) {
            root.right = sub(num, indexRoot+1, end);
        }

        return root;
    }
}

有什么辦法可以加快速度嗎? 謝謝。

組織自己的堆棧-索引對。 無需回程調用該過程,請使用堆棧放置對並為最頂層的對調用sub()。

while (stack of pairs processing is not finished) {
  //get next pair and process the pair
  sub(next pair);
}

public TreeNode sub(int[] num, int start, int end) {
    int indexRoot = (start+end+1) / 2;
    TreeNode root = new TreeNode(num[indexRoot]);

    if(indexRoot > start) {
        root.left = addToStack(num, 0, indexRoot-1);
    }
    if(indexRoot < end) {
        root.right = addToStack(num, indexRoot+1, end);
    }

    return root;
}

代碼中只有一個錯字。 正確的方法如下。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        if(num.length == 0) {
            return null;
        } else {
            return sub(num, 0, num.length-1);
        }
    }

    public TreeNode sub(int[] num, int start, int end) {
        int indexRoot = (start+end+1) / 2;
        TreeNode root = new TreeNode(num[indexRoot]);

        if(indexRoot > start) {
            root.left = sub(num, start, indexRoot-1);
        }
        if(indexRoot < end) {
            root.right = sub(num, indexRoot+1, end);
        }

        return root;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM