My Own Result due to the ideal in Leetcode 56


  • 0
    W

    /**

    • 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 List<Interval> insert(List<Interval> intervals, Interval newInterval) {
      List<Interval> res = new ArrayList<Interval>();
      if(intervals.size()==0){
      res.add(newInterval);
      return res;
      }
      Interval tempInterval = newInterval;
      for(Interval interval:intervals){
      if(cmp(tempInterval,interval)==-1){
      res.add(interval);
      continue;
      }
      else if(cmp(tempInterval,interval)==0){
      int start = Math.min(tempInterval.start,interval.start);
      int end = Math.max(tempInterval.end,interval.end);
      tempInterval = new Interval(start,end);
      }
      else{
      res.add(tempInterval);
      tempInterval = interval;
      }
      }
      res.add(tempInterval);
      return res;
      }

      public int cmp(Interval i1,Interval i2){
      if(i1.start>i2.end) return -1;
      if(i1.end<i2.start) return 1;
      return 0;
      }
      }


Log in to reply
 

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