Time Limit Exceeded Despite Using TreeMap? Why?


  • 0

    I keep getting time limit exceeded with my code but I do not understand why. I've looked at some of the other solutions that were accepted and they don't seem to differ too much from mine. Would someone mind please having a second look and giving some feedback?

    public class SummaryRanges {
        
        TreeMap<Integer,Interval> tm;
    
        /** Initialize your data structure here. */
        public SummaryRanges() {
            
            tm=new TreeMap<Integer,Interval>();
            
        }
        
        public void addNum(int val) {
            
           
           Interval i=new Interval(val,val);
           
           if(!tm.containsKey(val))
           {
               Map.Entry<Integer,Interval> c=tm.ceilingEntry(val);
           Map.Entry<Integer,Interval> f=tm.floorEntry(val);
           
            if(f==null||c==null)
            {
                tm.put(val,i);
            }else
            {
                int endFloor=f.getValue().end;
                int startCeil=c.getValue().start;
                if(!isOverlap(f.getValue(),i)||!isOverlap(c.getValue(),i))
                {
                    if(endFloor+1==val && startCeil-1==val)
                    {
                        f.getValue().end=c.getValue().end;
                        tm.remove(c.getKey());
                    }
                    else if (endFloor+1==val)
                    {
                        f.getValue().end=val;
                    }
                    else if(startCeil-1==val)
                    {
                       c.getValue().start=val;
                    }else
                    {
                        tm.put(val,i);
                    }
                }
            }
           }
            
        }
        
        public List<Interval> getIntervals() {
            List<Interval> ls=new ArrayList<Interval>(tm.values());
            return ls;
            
        }
        
        private boolean isOverlap(Interval x,Interval y)
        {
            return((x.end>=y.start && x.end<=y.end)||(y.end>=x.start && y.end<=x.end));
        }
      
    }

Log in to reply
 

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