Java 183ms simple solution without using any extra data structures.


  • 0
    L
    public class SummaryRanges {
        			
        			private List<Interval> intervals = new ArrayList<Interval>();
        		    /** Initialize your data structure here. */
        		    public SummaryRanges() {    		        
        		    }
        		    
        		     public void addNum(int val) {
        		        if (intervals.isEmpty()) intervals.add(new Interval(val, val));
        		        else {
        		        	for (int i = 0; i < intervals.size(); i++) {
        		        		Interval cur = intervals.get(i);    		        		
        		        		if (val == cur.start - 1) {
        		        			cur.start = val; 
        		        			return;
        		        		} else if (val < cur.start) {
        		        			intervals.add(i,new Interval(val, val));
        		        			return;
        		        		}	
        		        		else if (val >= cur.start && val <= cur.end) {  
        		        			return;
        		        		}
        		        		else if (val  == cur.end + 1) {
        		        			cur.end = val;
        		        			if (i + 1 < intervals.size()) {
        		        				Interval next = intervals.get(i + 1);
        		        				if (cur.end == next.start || cur.end == next.start -1) {
        		        					cur.end = next.end;
        		        					intervals.remove(i+1);    		        					
        		        				}    		        				
        		        			}
        		        			return;
        		        		}
        		        	}     	
        		        	
        		        	intervals.add(new Interval(val, val)); 	
        		        	
        		        }
        		    }
        		    
        		    
        		    public List<Interval> getIntervals() {
        		        return intervals;
        		    }
        		}
    

Log in to reply
 

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