Java TreeSet solution


  • 0
    Q
    public class SummaryRanges {
        public SummaryRanges() {
            
        }
        
        TreeSet<Integer> set = new TreeSet<>();
        public void addNum(int val) {
        	set.add(val);
        }
        
        public List<Interval> getIntervals() {
            List<Interval> list = new ArrayList<Interval>();
        	Iterator<Integer> iter = set.iterator();
        	int value = -999;
            while (iter.hasNext()){
            	int nextVal = iter.next();
        		if (nextVal != value+1)
        	    	list.add(new Interval(nextVal, nextVal));
        		list.get(list.size()-1).end=nextVal;
        		value = nextVal;
            }
            return list;
        }
    }

Log in to reply
 

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