깊은바다거북
개발 공부 기록
깊은바다거북
전체 방문자
오늘
어제
  • 분류 전체보기 (219)
    • JAVA (9)
    • JavaScript (15)
    • 스파르타코딩클럽 (11)
      • [내일배움단] 웹개발 종합반 개발일지 (5)
      • [내일배움캠프] 프로젝트와 트러블 슈팅 (6)
    • SQL | NoSQL (4)
    • CS 등등 (0)
    • TIL | WIL (173)
    • 기타 에러 해결 (3)
    • 내 살 길 궁리 (4)

인기 글

최근 글

최근 댓글

태그

  • 최소 힙(Min Heap)
  • 시간 복잡도
  • TypeScript
  • 트러블 슈팅 Troubleshooting
  • Linked List
  • TIT (Today I Troubleshot)
  • Binary Tree(이진 트리)
  • 자료 구조
  • 팀 프로젝트
  • 최대 힙(Max Heap)
  • BFS(너비우선탐색)
  • 점화식(Recurrence Relation)
  • DFS(깊이우선탐색)
  • Leetcode
  • leetcode-cli
  • tree
  • Preorder Traversal(전위 순회)
  • 자잘한 에러 해결
  • 코딩테스트 연습문제
  • BST(이진 탐색 트리)
  • Backtracking(백트래킹)
  • 재귀 함수
  • Trie
  • 프로그래머스
  • Inorder Traversal(중위 순회)
  • POST / GET 요청
  • 혼자 공부하는 자바스크립트
  • 자바스크립트 기초 문법
  • Til
  • 01. 미니 프로젝트
hELLO · Designed By 정상우.
깊은바다거북

개발 공부 기록

TIL | WIL

11/2 (목) 쿼리를 포함하기 위한 최소 인터벌 TIL

2023. 11. 2. 17:49

공부한 것

  • LeetCode #1851. Minimum Interval to Include Each Query
    Minimum Interval to Include Each Query - LeetCode
    Can you solve this real interview question? Minimum Interval to Include Each Query - You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1. Return an array containing the answers to the queries.   Example 1: Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] Output: [3,3,1,4] Explanation: The queries are processed as follows: - Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. Example 2: Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22] Output: [2,-1,4,6] Explanation: The queries are processed as follows: - Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.   Constraints: * 1 <= intervals.length <= 105 * 1 <= queries.length <= 105 * intervals[i].length == 2 * 1 <= lefti <= righti <= 107 * 1 <= queries[j] <= 107
    https://leetcode.com/problems/minimum-interval-to-include-each-query/description/?source=submission-noac
    • 최소 힙을 사용하니 걸리는 시간이 대폭 줄어들었다. ‘최소값’이라는 키워드가 나왔을 때 최소 힙을 떠올렸어야 했는데.
    • 해답 코드:
      function minInterval3(intervals: number[][], queries: number[]): number[] {
      	const sortedQueries = queries.map((q, i) => [q, i]).sort((a, b) => a[0] - b[0]);
      	intervals.sort((a, b) => a[0] - b[0]);
      
      	const heap = new MinHeap();
      	const result = new Array(queries.length);
      
      	let i = 0; 
      
      	for (const [query, index] of sortedQueries) {
      		while (i < intervals.length && intervals[i][0] <= query) {
      			const [start, end] = intervals[i];
      			heap.insert([end - start + 1, end]);
      			i++;
      		}
      
      		while (heap.size && query > heap.min[1]) {
      			heap.remove();
      		}
      
      		result[index] = heap.size ? heap.min[0] : -1;
      	}
      	
      	return result;
      }
      
      
      class MinHeap {
      	private heap: [number, number][] = [];
      
      	get min() {
      		return this.heap[0];
      	}
      
      	get size() {
      		return this.heap.length;
      	}
      
      	insert(val: [number, number]) {
      		this.heap.push(val);
      		this.bubbleUp(this.size - 1);
      	}
      
      	remove() {
      		if (!this.size) return;
      
      		this.swap(0, this.size - 1);
      		const min = this.heap.pop();
      		this.bubbleDown(0);
      		return min;
      	}
      
      	// 현재 index 자리의 노드를 min heap 규칙에 맞도록 끌어올린다.
      	private bubbleUp(index: number) {
      		// 지금 자리가 루트(root)에 도달하거나, 부모의 size값 이상이 될 때까지 반복 
      		while (index > 0) {
      			const parentIndex = Math.floor((index - 1) / 2);
      
      			// 지금 자리의 size값이 부모 자리의 size값보다 작을 때만 자리 교체
      			if (this.heap[index][0] < this.heap[parentIndex][0]) {
      				this.swap(index, parentIndex);
      				index = parentIndex;
      			} else {
      				break;
      			}
      		}
      	}
      
      	// 현재 index 자리의 노드를 min heap 규칙에 맞도록 끌어내린다.
      	private bubbleDown(index: number) {
      		// 지금 자리가 힙의 끝에 도달하거나, 두 자식의 size값 미만이 될 때까지 반복
      		while (index < this.size) {
      			const leftChildIndex = index * 2 + 1;
      			const rightChildIndex = index * 2 + 2;
      			let smallest = index;
      
      			if (leftChildIndex < this.size && this.heap[leftChildIndex][0] < this.heap[smallest][0])
      				smallest = leftChildIndex;
      			
      			if (rightChildIndex < this.size && this.heap[rightChildIndex][0] < this.heap[smallest][0])
      				smallest = rightChildIndex;
      
      			if (index === smallest) break;
      
      			this.swap(index, smallest);
      			index = smallest;
      		}
      	}
      
      	private swap(i: number, j: number) {
      		[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
      	}
      }


Uploaded by N2T

    'TIL | WIL' 카테고리의 다른 글
    • 11/14 (화) 대소문자를 모두 가지는 최장 부분 문자열 구하기 TIL
    • 11/3 (금) 합이 가장 큰 부분 배열 TIL
    • 10/28 (토) (완료)인터벌이 안 겹치도록 삭제해야 하는 최소 인터벌 개수 TIL
    • 10/27 (금) 인터벌이 안 겹치도록 삭제해야 하는 최소 인터벌 개수 TIL
    깊은바다거북
    깊은바다거북

    티스토리툴바