Skip to content

Conversation

@alexgoni
Copy link
Contributor

📌 푼 문제

문제이름 문제링크
Merge Intervals https://leetcode.com/problems/merge-intervals
Min Cost to Connect all points https://leetcode.com/problems/min-cost-to-connect-all-points
Lowest Common ancestor of a Binary Search Tree https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree
Word Break https://leetcode.com/problems/word-break
Kth largest element in an Array https://leetcode.com/problems/kth-largest-element-in-an-array

📝 간단한 풀이 과정

56. Merge Intervals

각 배열의 첫 번째 인수를 기준으로 오름차순 정렬하고,
겹치는 경우 splice하여 intervals를 계속해서 편집해나가는 방식으로 풀었습니다.

/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function (intervals) {
  const result = [];
  intervals.sort((a, b) => a[0] - b[0]);

  let i = 0;
  while (i < intervals.length - 1) {
    if (intervals[i][1] >= intervals[i + 1][0]) {
      intervals.splice(i, 2, [
        intervals[i][0],
        Math.max(intervals[i][1], intervals[i + 1][1]),
      ]);
    } else {
      i++;
    }
  }

  return intervals;
};

1584. Min Cost to Connect all points

제일 어려운 문제였어요
MST 문제라고 하는데 Kruskal이랑 Prim 알고리즘이 있다고 합니다..
아래는 Prim 알고리즘 풀이입니다.

// 😢

/**
 * @param {number[][]} points
 * @return {number}
 */
var minCostConnectPoints = function (points) {
  const n = points.length;
  const visited = Array(n).fill(false);
  const minDist = Array(n).fill(Infinity);
  minDist[0] = 0;
  let result = 0;

  for (let i = 0; i < n; i++) {
    let currMin = Infinity;
    let currNode = -1;

    for (let j = 0; j < n; j++) {
      if (!visited[j] && minDist[j] < currMin) {
        currMin = minDist[j];
        currNode = j;
      }
    }

    visited[currNode] = true;
    result += currMin;

    for (let j = 0; j < n; j++) {
      if (!visited[j]) {
        const cost =
          Math.abs(points[currNode][0] - points[j][0]) +
          Math.abs(points[currNode][1] - points[j][1]);
        minDist[j] = Math.min(minDist[j], cost);
      }
    }
  }

  return result;
};

235. Lowest Common ancestor of a Binary Search Tree

BST의 특징을 활용하여 푸는 문제였습니다.

// 😢

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (root, p, q) {
  if (p.val < root.val && q.val < root.val) {
    return lowestCommonAncestor(root.left, p, q);
  }

  if (p.val > root.val && q.val > root.val) {
    return lowestCommonAncestor(root.right, p, q);
  }

  return root;
};

139. Word Break

이것도 dp 문제일 줄을 몰랐어요;;

// 😢

/**
 * @param {string} s
 * @param {string[]} wordDict
 * @return {boolean}
 */
var wordBreak = function (s, wordDict) {
  const wordSet = new Set(wordDict);
  const dp = Array.from({ length: s.length + 1 }).fill(false);
  dp[0] = true;

  for (let i = 1; i <= s.length; i++) {
    for (let j = 0; j < i; j++) {
      if (dp[j] && wordSet.has(s.slice(j, i))) {
        dp[i] = true;
        break;
      }
    }
  }

  return dp[s.length];
};

150. Kth largest element in an Array

Heap을 사용하여 풀었습니다.

// 😢

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findKthLargest = function (nums, k) {
  const heap = new MaxBinaryHeap();

  for (const num of nums) {
    heap.insert(num);
  }

  for (let i = 0; i < k; i++) {
    const extractedValue = heap.extractMax();
    if (i === k - 1) return extractedValue;
  }
};

class MaxBinaryHeap {
  constructor() {
    this.values = [];
  }

  insert(value) {
    this.values.push(value);
    this.#bubbleUp();

    return this.values;
  }

  extractMax() {
    const extractedValue = this.values[0];
    const poppedValue = this.values.pop();

    if (this.values.length === 0) return extractedValue;

    this.values[0] = poppedValue;
    this.#sinkDown();

    return extractedValue;
  }

  #bubbleUp() {
    let currentIndex = this.values.length - 1;
    const currentValue = this.values[currentIndex];

    while (currentIndex > 0) {
      const parentIndex = Math.floor((currentIndex - 1) / 2);
      const parentValue = this.values[parentIndex];

      if (parentValue >= currentValue) break;

      this.values[parentIndex] = currentValue;
      this.values[currentIndex] = parentValue;

      currentIndex = parentIndex;
    }
  }

  #sinkDown() {
    let currentIndex = 0;
    const currentValue = this.values[currentIndex];
    const length = this.values.length;

    while (true) {
      let leftChildIndex = currentIndex * 2 + 1;
      let rightChildIndex = currentIndex * 2 + 2;
      let leftChildValue, rightChildValue;
      let swapWith = null;

      if (leftChildIndex < length) {
        leftChildValue = this.values[leftChildIndex];
        if (leftChildValue > currentValue) swapWith = leftChildIndex;
      }

      if (rightChildIndex < length) {
        rightChildValue = this.values[rightChildIndex];
        if (
          (!swapWith && rightChildValue > currentValue) ||
          (swapWith && rightChildValue > leftChildValue)
        ) {
          swapWith = rightChildIndex;
        }
      }

      if (!swapWith) break;

      this.values[currentIndex] = this.values[swapWith];
      this.values[swapWith] = currentValue;

      currentIndex = swapWith;
    }
  }
}

@alexgoni alexgoni self-assigned this Nov 26, 2024
@oris8 oris8 requested review from dudwns0213 and wjsdncl November 26, 2024 14:04
@oris8 oris8 merged commit c9840fb into master Dec 2, 2024
3 checks passed
JooKangsan pushed a commit that referenced this pull request Dec 3, 2024
* 56 / Merge Intervals / Medium / 30m

* 1584 / Min Cost to Connect All Points / Medium

* 235 / Lowest Common Ancestor of a Binary Search Tree / Medium

* 139 / Word Break / Medium

* 215 / Kth Largest Element in an Array / Medium
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants