数组变MaxTree-java

public int[] buildMaxTree(int[] A, int n) {
        // write code here
        if (A == null || n < 1) {
            return null;
        }
        Stack<Integer>  findStack = new Stack<Integer>();
        Integer[] leftMax  = new Integer[n];
        Integer[] rightMax = new Integer[n];
         
         
        for (int i = 0; i < n; i++) {
            while (!findStack.empty() && A[findStack.peek()] <= A[i]) {
                findStack.pop();
            }
            if (findStack.empty())
                leftMax[i] = null;
            else
                leftMax[i] = findStack.peek();
            findStack.push(new Integer(i));
        }
         
        while (!findStack.empty()) {
            findStack.pop();
        }
         
        for (int i = n - 1; i >= 0; i--) {
            while (!findStack.empty() && A[findStack.peek()] <= A[i]) {
                findStack.pop();
            }
            if (findStack.empty())
                rightMax[i] = null;
            else
                rightMax[i] = findStack.peek();
            findStack.push(new Integer(i));
        }
         
        int[] res = new int[n];
        int j = 0;
        for (int i = 0; i < n; ++i) {
            if (leftMax[i] != null && rightMax[i] != null) {
                if (A[leftMax[i]] < A[rightMax[i]])
                    res[j++] = leftMax[i];
                else
                    res[j++] = rightMax[i];
            }
            else if (leftMax[i] != null && rightMax[i] == null) {
                res[j++] = leftMax[i];
            }
            else if (leftMax[i] == null && rightMax[i] != null) {
                res[j++] = rightMax[i];
            }
            else {
                res[j++] = -1;
            }
        }
         
        return res;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值