在递归中实现代码

时间:2015-11-21 07:00:47

标签: java recursion

我在递归中实现代码时遇到问题。 我不会那样以这种方式思考。

这里是我编写的一个代码,用于以O(n + logn)比较的方式找到数组中的2个最大数字,并且现在我也希望以递归方式实现。 你能指点一下吗? 提前谢谢。

这是我的归纳代码:

package MyPackage;

import java.util.Arrays;
import java.util.Stack;

public class BestIndSol {

    class NodeCircle{
        private int max;
        private Stack<Integer> max2;
        private NodeCircle next;
        private NodeCircle prev;

        public NodeCircle(int max,NodeCircle next, NodeCircle prev){
            this.max=max;
            this.max2 = new Stack <Integer>();
            this.next = next;
            this.prev = prev;
        }
        public void addmax2(int num){
            this.max2.add(num);
        }
        public int getMax() {
            return max;
        }
        public void setMax(int max) {
            this.max = max;
        }
        public int Max2(){
            int maxs = Integer.MIN_VALUE;
            if(!this.max2.isEmpty())
            maxs = (this.max2.pop());
            while(!this.max2.isEmpty()){
                if(maxs<this.max2.peek())
                    maxs = this.max2.pop();
                else
                    this.max2.pop();
            }
            return maxs;    
        }
    }
    public NodeCircle Array2CircledLL(int[] arr){
        NodeCircle head  = new NodeCircle(arr[0],null,null);
        NodeCircle temp = head;
        NodeCircle Now=null;
        for(int i = 1;i<arr.length;i++){
            Now = new NodeCircle(arr[i], null,temp );
            temp.next = Now;
            temp=temp.next;
        }
        Now.next = head;
        head.prev = Now;
        return head;
    }
    public static int [] randarr(int size){
        int [] arr = new int[size];
        for(int i =0;i<size;i++){
            arr[i] = (int)(Math.random()*1000);
        }
        return arr;
    }
    public void TheSolution(){
        int[] a = randarr(100);
        int size = a.length;
        NodeCircle c = Array2CircledLL(a);
        System.out.println("Array is:" + Arrays.toString(a));
        NodeCircle temp1= c;
        NodeCircle temp2  = null;
        while(size>1){
            temp2 = temp1.next;
            if(temp1.max>temp2.max){
                temp1.max2.push(temp2.max);
                temp1.next = (temp2.next);
                temp2.next.prev = temp1;
                temp1=temp1.next;
                size--;

            }
            else{
                temp2.max2.push(temp1.max);
                temp2.prev = (temp1.prev);
                temp1.prev.next = temp2;
                temp1=temp1.next;
                size--;
            }
        }
        System.out.println("max is:" + temp1.max);

        System.out.println("Max2 is: "+temp1.Max2());
    }


    public static void main(String[] args) {
        BestIndSol s = new BestIndSol();
        s.TheSolution();

    }

}

0 个答案:

没有答案