베어_
TechBear
베어_
전체 방문자
오늘
어제
  • 분류 전체보기 (336)
    • Spring (33)
      • 개념 (13)
      • Security (5)
      • 실습 (1)
      • 토비 스프링 (11)
    • JPA (6)
    • 프로젝트 기록 (24)
    • DB (13)
    • JAVA (18)
    • 알고리즘 (50)
      • 유형정리 (8)
      • Baekjoon (21)
      • LeetCode (18)
    • 디자인패턴 (0)
    • 개발서적 (79)
      • Effective Java (78)
      • 객체지향의 사실과 오해 (1)
    • 독후감 (4)
    • 보안 (2)
    • 운영체제(OS) (53)
      • 공룡책 (53)
    • 컴퓨터 네트워크 (28)
      • 컴퓨터 네트워크 하향식 접근 (23)
    • 자료구조 (1)
    • DevOps (2)
    • 앱 개발 (20)
      • 안드로이드 스튜디오 (20)

블로그 메뉴

    공지사항

    인기 글

    태그

    • 코드업
    • 이펙티브자바
    • 함수형인터페이스
    • 자바8
    • jpa
    • 스프링시큐리티
    • 운영체제
    • 스프링
    • 토비스프링
    • dfs
    • C++
    • java
    • 스레드
    • Spring
    • leetcode
    • 데이터베이스
    • 백준
    • BFS
    • 알고리즘
    • 자바

    최근 댓글

    최근 글

    티스토리

    hELLO · Designed By 정상우.
    베어_

    TechBear

    알고리즘/LeetCode

    [LeetCode] Insert Interval

    2023. 7. 24. 16:28

    ✉️문제

    https://leetcode.com/problems/insert-interval/description/

     

    Insert Interval - LeetCode

    Can you solve this real interview question? Insert Interval - You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order b

    leetcode.com

     

    🗝 문제풀이

        겹치는 부분의 조건을 확인하고 겹칠 때 마다 newInterval을 업데이트 한다.

    class Solution {
        public int[][] insert(int[][] intervals, int[] newInterval) {
            List<int[]> res = new ArrayList<>();
            for(int i = 0; i < intervals.length; i++) {
                if(newInterval[1] < intervals[i][0]) {
                    res.add(new int[] {newInterval[0], newInterval[1]});
                    for(int j = i; j < intervals.length; j++) {
                        res.add(intervals[j]);
                    }
                    return toArray(res);
                } else if(intervals[i][1] < newInterval[0]) {
                    res.add(new int[] {intervals[i][0], intervals[i][1]});
                } else { // 겹치는 경우 
                    int left = Math.min(intervals[i][0], newInterval[0]);
                    int right = Math.max(intervals[i][1], newInterval[1]);
                    newInterval = new int[] {left, right};
                }
            }
    
            res.add(newInterval);
    
            return toArray(res);
        }
    
        private static int[][] toArray(List<int[]> res) {
            int[][] answer = new int[res.size()][2];
            for (int i = 0; i < res.size(); i++) {
                answer[i] = res.get(i);
            }
            return answer;
        }
    }
    저작자표시 비영리 변경금지 (새창열림)
      '알고리즘/LeetCode' 카테고리의 다른 글
      • [LeetCode] Course Schedule (Java)
      • [LeetCode] Clone Graph (Java)
      • [LeetCode] Reorder List (Java)
      • [LeetCode] Merge Two Sorted Lists (Java)
      베어_
      베어_
      Today I learned | 문제를 해결하는 개발자

      티스토리툴바