Any suggestions for my simple Java solution?


  • 0
    Y

    public List<Interval> merge(List<Interval> intervals) {

        if(intervals.size() == 0)
        	return new ArrayList<Interval>();
        List<Interval> result = new ArrayList<Interval>();
        
        int size = intervals.size();
        Comparator<Interval> comparator = new Comparator<Interval>() {
        	public int compare(Interval I1, Interval I2) {
        		return I1.start - I2.start;
        	}
    	};
    	Collections.sort(intervals, comparator);
    	
        int start = intervals.get(0).start;
        int end = intervals.get(0).end;
        for(int i=1; i<size; i++) {
        	if(end >= intervals.get(i).start) {
        		start = start<intervals.get(i).start ? 
        				start : intervals.get(i).start;
        		end = end>intervals.get(i).end ? end : intervals.get(i).end;
        	} else {
        		result.add(new Interval(start, end));
        		start = intervals.get(i).start;
        		end = intervals.get(i).end;
        	}
        }
        result.add(new Interval(start, end));
        return result;
    }

  • 0
    A

    I think "start = start<intervals.get(i).start ? start : intervals.get(i).start" can be deleted.


  • 0
    Y

    Yeah, you are right. Thanks for your suggestion.


Log in to reply
 

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