Help with code, results appeared differently


  • 0
    P

    I am new to Java, so I wrote the following code and it worked fine on my computer but when I run it on OJ, it gave me the following error:

    Input: addNum(2),findMedian(),addNum(3),findMedian()
    Output: [0.00000,0.00000]
    Expected: [2.00000,2.50000] 
    

    But I indeed got 2.0, 2.5 on my computer.
    Here is my code:

    public class A{
        public static void main(String[] args) {
    		MedianFinder mf = new MedianFinder();
    		mf.addNum(2);
    		System.out.println(mf.findMedian());
    		mf.addNum(3);
    		System.out.println(mf.findMedian());
    	}
    }
    import java.util.ArrayList;
    class MedianFinder {
    	static ArrayList<Integer> al = new ArrayList<Integer>();
    	static double median = 0;
        // Adds a number into the data structure.
        public void addNum(int num) {
            al.add(num);
        }
        // Returns the median of current data stream
        public double findMedian() {
        	
        	if(al.size()<1){
        		median = 0;
        	}else if(al.size()==1){
        		median = al.get(0);
        	}else{
        		int index = al.size()/2;
        		if(al.size()%2==0){
        			median = (double) (al.get(index)+al.get(index-1))/2; 
        		}else{
        			median = (int) al.get(index);
        		}
        	}
         return median;
        }
    };
    

    Please help me understand, thank you.


  • 0

    Why do you make those fields static? Makes no sense, and causes your problem.


  • 0
    P

    Thank you stefan, but why did those static variable cause the problem?


  • 0
    G

    Your problem is that numbers are not getting added in sorted order.You are not maintaining counter of how many elements added


  • 0

    @primenumber123 Because the OJ of course doesn't reload your class between the test cases or whatever else would reset those fields, and you're not resetting them yourself, either. Still wondering why you made them static in the first place.


  • 0
    P

    @grvchik, yes, I am working on that part, I thought a Hard question shouldn't be solved by my naive way of thinking. Thank you.
    @StefanPochmann, thank you so much, I made them static because at the beginning I was writing something in the static main method, then I changed a lot and forgot about it. Thanks again.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.