java easy simple use stack


  • 0
    G
    /**
     * Definition for an interval.
     * public class Interval {
     *     int start;
     *     int end;
     *     Interval() { start = 0; end = 0; }
     *     Interval(int s, int e) { start = s; end = e; }
     * }
     */
    public class Solution {
        public static List<Interval> merge(List<Interval> intervals) {
            
    		List<Interval> res = new ArrayList<>();
    		
            Collections.sort(intervals, new Comparator<Interval>(){
                public int compare(Interval i1, Interval i2){
                    if(i1.start==i2.start){
                        return i1.end-i2.end;
                    }
                    return i1.start-i2.start;
                }
            });
          
            Stack<Interval> sk = new Stack<>();
            
            for(int i=intervals.size()-1;i>=0;i--){
            	sk.push(intervals.get(i));
            }
            
            while(!sk.isEmpty()){
            	Interval temp = sk.pop(); 
            	if(!sk.isEmpty() && temp.end >= sk.peek().start){ 
            		Interval temp1 = sk.pop();
            		if(temp.end<=temp1.end){
            		    sk.push(new Interval(temp.start,temp1.end));
            		}
            		else{
            		    sk.push(new Interval(temp.start,temp.end));
            		}
            	}else{
            		res.add(temp);
            	}    	
            }
            return res;
        }
    }

Log in to reply
 

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