Unable to understand input which is being fed


  • -1
    V

    I am using following code. When input is [[1,3]], it is saying that my program is returning null but it expects [[1,3]]. In my local, i tested by program in which input linked list ,intervals, contains one interval (1,3). It is returning [1,3]. I need help in understanding what is meant by [[1,3]]. I am considering it a list which contains one interval [1,3]
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;

    class Interval {
    int start;
    int end;

    Interval() {
    	start = 0;
    	end = 0;
    }
    
    Interval(int s, int e) {
    	start = s;
    	end = e;
    }
    

    }

    class intervalSort implements Comparator<Interval>{

    @Override
    public int compare(Interval arg0, Interval arg1) {
    	// TODO Auto-generated method stub
    	return arg0.start-arg1.start;
    }
    

    }

    public class MergeIntervals {

    public static void main(String args[]){
    	MergeIntervals merge = new MergeIntervals();
    	List<Interval> intervals= new ArrayList<Interval>();
    	/*intervals.add(new Interval(1,4));
    	intervals.add(new Interval(3,6));
    	intervals.add(new Interval(2,3));*/
    	/*intervals.add(new Interval(1,3));*/
    	intervals.add(new Interval(1,3));
    	intervals.add(new Interval(2,6));
    	intervals.add(new Interval(8,10));
    	intervals.add(new Interval(15,18));
    	
    	System.out.println("Before merge:");
    	for(Interval interval: intervals){
    		System.out.println("Start index "+interval.start+" end index "+interval.end+"\n");
    	}
    	
    	merge.merge(intervals);
    	
    	System.out.println("After merge:");
    	for(Interval interval: intervals){
    		System.out.println("Start index "+interval.start+" end index "+interval.end+"\n");
    	}
    }
    
    public List<Interval> merge(List<Interval> intervals) {
    	if(intervals==null || intervals.size()==0){
    		return intervals;
    	}
    
    	Collections.sort(intervals,new intervalSort());
    	
    	for(int i=0;i<intervals.size();i++){
    		int start = intervals.get(i).start;
    		int end = intervals.get(i).end;
    		int originalEnd=end;
    		int j=i+1;
    		while (true){
    			if(j==intervals.size())
    			{
    				if(end!=originalEnd){
    					intervals.remove(i);
    					intervals.add(i, new Interval(start,end));
    				}
    				break;
    			}
    			if(end>=intervals.get(j).start){
    				end=Math.max(end, intervals.get(j).end);
    				intervals.remove(j);
    			}else{
    				if(end!=originalEnd){
    					intervals.remove(i);
    					intervals.add(i, new Interval(start,end));
    				}
    				break;
    			}
    		}
    	}
    	
    	return null;
    }
    

    }


Log in to reply
 

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