刷题(一)

Merge Interval笔记整理

Posted by Seven.. on Monday, March 13, 2023

Conditions

conditions

Questions

  • 56

    •  class Solution {
           public int[][] merge(int[][] intervals) {
               //sort
               Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
               List<int[]> merged = new ArrayList<>();    
               for(int[]interval:intervals){
                   //empty(),arraylist get last element =merged.size()-1
                   if( merged.isEmpty() || merged.get(merged.size()-1)[1] < interval[0]){
                   merged.add(interval); 
                   }else if(merged.get(merged.size()-1)[1] >= interval[0] ){
                       merged.get(merged.size()-1)[1] = Math.max(merged.get(merged.size()-1)[1],interval[1] );
                   }
               }
           //toArray(new int[][]) 
           return merged.toArray(new int[merged.size()][2]);
      
           }
       }
      
    • Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
      Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
  • 57

    •  class Solution {
           public int[][] insert(int[][] intervals, int[] newInterval) {
               List<int[]> result = new ArrayList<>();
           int i = 0;
           int n = intervals.length;
      
           // add all intervals before newInterval
           while (i < n && intervals[i][1] < newInterval[0]) {
               result.add(intervals[i]);
               i++;
           }
      
           // merge overlapping intervals
           while (i < n && intervals[i][0] <= newInterval[1]) {
               newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
               newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
               i++;
           }
      
           // add merged interval
           result.add(newInterval);
      
           // add remaining intervals
           while (i < n) {
               result.add(intervals[i]);
               i++;
           }
      
           // convert list to array
           return result.toArray(new int[result.size()][2]);
           }
       }
      
  • 252

    • class Solution {
          public boolean canAttendMeetings(int[][] intervals) {
              // Sort the intervals in ascending order of start time
              Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
              // Check if any two consecutive meetings overlap
              for (int i = 0; i < intervals.length - 1; i++) {
                  if (intervals[i][1] > intervals[i+1][0]) {
                      return false;
                  }
              }
      
              // If no overlapping meetings found, return true
              return true;
          }
      
      
  • 253

    • class Solution {
          public int minMeetingRooms(int[][] intervals) {
              // Sort the intervals in ascending order of start time
          Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
      
          // Use a priority queue to keep track of end times
          PriorityQueue<Integer> endTimes = new PriorityQueue<>();
      
          // Add the end time of the first meeting to the priority queue
          endTimes.add(intervals[0][1]);
      
          // Iterate over the remaining meetings and update the priority queue
          for (int i = 1; i < intervals.length; i++) {
              if (intervals[i][0] >= endTimes.peek()) {
                  // If the start time of the current meeting is later than or equal to the earliest ending meeting,
                  // remove the earliest ending meeting from the priority queue and add the end time of the current meeting
                  endTimes.poll();
              }
              endTimes.add(intervals[i][1]);
          }
      
          // Return the size of the priority queue, which represents the minimum number of conference rooms required
          return endTimes.size();
      
      
          }
      }
      
  • 435

    • class Solution {
          public int eraseOverlapIntervals(int[][] intervals) {
              // Sort the intervals in ascending order of end time
          Arrays.sort(intervals, (a, b) -> a[1] - b[1]);
      
          int count = 0;
          int end = Integer.MIN_VALUE;
      
          // Iterate over the intervals and count the number of overlapping intervals
          for (int[] interval : intervals) {
              if (interval[0] >= end) {
                  // If the start time of the current interval is later than or equal to the end time of the previous interval,
                  // update the end time and increment the count of non-overlapping intervals
                  end = interval[1];
                  count++;
              }
          }
      
          // Return the number of removed intervals, which is the difference between the total number of intervals and the count of non-overlapping intervals
          return intervals.length - count;
          }
      }
      
  • 759

    • // // Definition for an Interval.
      // class Interval {
      //     public int start;
      //     public int end;
      
      //     public Interval() {}
      
      //     public Interval(int _start, int _end) {
      //         start = _start;
      //         end = _end;
      //     }
      // };
      
      
      class Solution {
          public List<Interval> employeeFreeTime(List<List<Interval>> schedule) {
          // Use a priority queue to keep track of the next earliest ending interval
              PriorityQueue<Interval> pq = new PriorityQueue<>((a, b) -> a.start - b.start);
      
              // Add all intervals from all employees to the priority queue
              for (List<Interval> intervals : schedule) {
                  pq.addAll(intervals);
              }
      
              List<Interval> result = new ArrayList<>();
              Interval prev = pq.poll();
      
              // Iterate over the intervals in the priority queue and find the free time intervals
              while (!pq.isEmpty()) {
                  Interval current = pq.poll();
                  if (prev.end < current.start) {
                      // If there is a gap between the end of the previous interval and the start of the current interval,
                      // add a free time interval to the result
                      result.add(new Interval(prev.end, current.start));
                      prev = current;
                  } else {
                      // Otherwise, update the previous interval if the end time of the current interval is later
                      if (prev.end < current.end) {
                          prev.end = current.end;
                      }
                  }
              }
      
              return result;  
          }
      }
      
  • 986

    • class Solution {
      public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
          List<int[]> result = new ArrayList<>();
          int i = 0, j = 0;
      
          // Iterate over both lists of intervals and find the intersections
          while (i < firstList.length && j < secondList.length) {
              // Find the start and end of the intersection
              int start = Math.max(firstList[i][0], secondList[j][0]);
              int end = Math.min(firstList[i][1], secondList[j][1]);
      
              if (start <= end) {
                  // If there is an intersection, add it to the result
                  result.add(new int[]{start, end});
              }
      
              // Move to the next interval with the smaller end time
              if (firstList[i][1] < secondList[j][1]) {
                  i++;
              } else {
                  j++;
              }
          }
      
          // Convert the result to a 2D array and return it
          return result.toArray(new int[result.size()][]);
          }
      }
      
  • 1094

    •     class Solution {
          public boolean carPooling(int[][] trips, int capacity) {
              // Create a timeline of events
              List<int[]> events = new ArrayList<>();
              for (int[] trip : trips) {
                  events.add(new int[]{trip[1], trip[0]});
                  events.add(new int[]{trip[2], -trip[0]});
                  // Each trip has two events: a pickup event and a dropoff event
                  // The pickup event adds the number of passengers to the car
                  // The dropoff event subtracts the number of passengers from the car
              }
              // Sort the events in ascending order of their locations
              Collections.sort(events, (a, b) -> a[0] - b[0]);
      
              // Check the number of passengers at each location
              int passengers = 0;
              for (int[] event : events) {
                  passengers += event[1];
                  if (passengers > capacity) {
                      // If the number of passengers exceeds the car's capacity, return false
                      return false;
                  }
              }
      
              // If the function reaches this point, all trips can be completed
              return true;
          }
      }
      
  • 1109

    •     class Solution {
          public int[] corpFlightBookings(int[][] bookings, int n) {
              // Create an array to store the result
              int[] result = new int[n];
      
              // Iterate through each booking
              for (int[] booking : bookings) {
                  // Extract the start, end, and seats values from the booking
                  int start = booking[0];
                  int end = booking[1];
                  int seats = booking[2];
      
                  // Add the seats to the result array for each flight in the booking range
                  for (int i = start; i <= end; i++) {
                      result[i - 1] += seats;
                  }
              }
      
              return result;
          }
      }
      
  • 495

    • class Solution {
          public int findPoisonedDuration(int[] timeSeries, int duration) {
              int n = timeSeries.length;
          if (n == 0) { // if there are no attacks, Ashe is not poisoned
              return 0;
          }
          int total = 0;
          for (int i = 0; i < n - 1; i++) { // iterate over all attacks except the last one
              total += Math.min(timeSeries[i+1] - timeSeries[i], duration); // add the duration of poison for each attack
          }
          return total + duration; // add duration of poison for the last attack
          }
      }
      
  • 616

    • class Solution {
          public String addBoldTag(String s, String[] words) {
              int n = s.length();
              boolean[] bold = new boolean[n];
      
              // Mark all positions where words occur in s as bold
              for (String word : words) {
                  int idx = s.indexOf(word);
                  while (idx != -1) {
                      for (int i = idx; i < idx + word.length(); i++) {
                          bold[i] = true;
                      }
                      idx = s.indexOf(word, idx + 1);
                  }
              }
      
              // Insert bold tags at appropriate positions
              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < n; i++) {
                  if (bold[i] && (i == 0 || !bold[i-1])) {
                      sb.append("<b>");
                  }
                  sb.append(s.charAt(i));
                  if (bold[i] && (i == n-1 || !bold[i+1])) {
                      sb.append("</b>");
                  }
              }
      
              return sb.toString();
          }
      }
      

Conclusion

「少种的少收,多种的多收,捐款会鼓励作者多创作以及教会福音传播!!」

少种的少收,多种的多收,捐款会鼓励作者多创作以及教会福音传播!!

使用微信扫描二维码完成支付