HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
👻
개발 기록
/
코딩테스트 스터디
코딩테스트 스터디
/
Non-overlapping Intervals

Non-overlapping Intervals

Link
https://leetcode.com/problems/non-overlapping-intervals/
Deadline
Oct 2, 2022
Status
Archived
Type
greedy
dynamic programming

문제

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: intervals = [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
Example 2:
Input: intervals = [[1,2],[1,2],[1,2]] Output: 2 Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.
Example 3:
Input: intervals = [[1,2],[2,3]] Output: 0 Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Constraints:
  • 1 <= intervals.length <= 105
  • intervals[i].length == 2
  • 5 * 104 <= starti < endi <= 5 * 104

풀이

효성
var eraseOverlapIntervals = function(intervals) { let answer = 0; intervals.sort((a, b) => a[1] - b[1]); for(let i = 0; i < intervals.length - 1; i++) { const [curStart, curEnd] = intervals[i]; const [nextStart, nextEnd] = intervals[i + 1]; if(curEnd > nextStart) { answer += 1; intervals[i + 1] = intervals[i]; } } return answer; };
  • end 값으로만 정렬해도 되는 이유 : end를 기점으로 start가 값이 무엇이든 잘리게 되어있음.
재영
/** * @param {number[][]} intervals * @return {number} */ const getSortedArray = (arr, func) => { return [...arr].sort(func); }; const eraseOverlapIntervals = (intervals) => { let answer = 0; const sortedIntervals = getSortedArray(intervals, (a, b) => a[1] - b[1]); let last = -50000; // 마지막에 기억하고 있는 엔드값. sortedIntervals.forEach(([from, to]) => { if (from < last) { answer += 1; } else { last = to; // 겹치지 않을 때만 업데이트를 해주는 이유 } }); return answer; };