My easy understanding java solution ( also my first time to submit my solution)


  • 0
    W

    public class SummaryRanges {
    Interval interval;
    List<Interval> list;
    /** Initialize your data structure here. */
    public SummaryRanges() {
    list = new ArrayList<>();
    }

    public void addNum(int val) {
        boolean addnew=true;
        int insertposition=0;
        for(int i=0;i<list.size();i++){
            if(val>=list.get(i).start&&val<=list.get(i).end){
                addnew=false;
                break;
            }
            else if(val==list.get(i).start-1){
                list.get(i).start=val;
                addnew=false;
                break;
            }
            else if(val==list.get(i).end+1){
                list.get(i).end=val;
                addnew=false;
                break;
            }
            if(val>list.get(i).end){
                insertposition=i+1;
            }
        }
        if(addnew){
            interval=new Interval();
            list.add(insertposition,interval);
            list.get(insertposition).start=val;
            list.get(insertposition).end=val;
        }
        else{
            int first=0,second=1;
            while(second<list.size()){
                if(list.get(first).end+1==list.get(second).start){
                    list.get(first).end=list.get(second).end;
                    list.remove(second);
                }
                else{
                    first++;
                    second++;
                }
            }
        }
    }
    
    public List<Interval> getIntervals() {
        return list;
    }
    

    }

    I didn't use binary search tree. Main idea for add function is

    1. if the value is new (meaning it cannot be add to any existed set) , add it in the list in the right position to keep ascending order.

    2. if the value is added or included in any set, then it should be checked for each set in the list to see whether any two set could be combined.

    Hopefully my code will be still accepted in the future as more test groups are added.


Log in to reply
 

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