Skip to content

Conversation

@CitrusSoda
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

prev라는 배열 하나를 이용하여 겹쳐지면 push하여 추가하는 방식으로 구현하였습니다.

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

  const ans = [];
  let prev = intervals[0];

  for (let i = 1; i < intervals.length; i++) {
    let interval = intervals[i];

    if (interval[0] <= prev[1]) {
      prev[1] = Math.max(prev[1], interval[1]);
    } else {
      ans.push(prev);
      prev = interval;
    }
  }

  ans.push(prev);
  return ans;
};

1584. Min Cost to Connect all points

프림 알고리즘을 알고있는지 물어보는 문제였습니다.
노드를 천천히 최소 거리로 잇고 거리를 구하는 로직입니다.

/**
 * @param {number[][]} points
 * @return {number}
 */
// Prim's Algorithm
var minCostConnectPoints = function (points) {
  const n = points.length;

  // 방문 여부를 체크하는 배열
  const visited = new Set();

  // 각 점까지의 최소 거리를 저장하는 배열
  const distances = new Array(n).fill(Infinity);
  distances[0] = 0;

  let totalCost = 0;

  for (let i = 0; i < n; i++) {
    let minDist = Infinity;
    let minIndex = -1;

    // 아직 방문하지 않은 점들 중에서 최소 거리를 가진 점을 찾음
    for (let j = 0; j < n; j++) {
      if (!visited.has(j) && distances[j] < minDist) {
        minDist = distances[j];
        minIndex = j;
      }
    }

    visited.add(minIndex);
    totalCost += minDist;

    // 선택된 점에서 다른 모든 점까지의 거리를 업데이트
    for (let j = 0; j < n; j++) {
      if (!visited.has(j)) {
        const distance =
          Math.abs(points[minIndex][0] - points[j][0]) +
          Math.abs(points[minIndex][1] - points[j][1]);
        distances[j] = Math.min(distances[j], distance);
      }
    }
  }

  return totalCost;
};

235. Lowest Common ancestor of a Binary Search Tree

알고리즘을 만드는 문제라기 보단 LCA를 이해하고 있나 물어보는 문제인 것 같았습니다.
이진트리라는 점을 이용하여 왼쪽에는 더 작은 노드, 오른쪽은 더 큰 노드이므로 루트노드가 p보다 크고 q보다 작을때 return시키면 되므로 재귀로 위에서부터 아래로 찾아가는 알고리즘입니다.

/**
 * 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 (root.val > p.val && root.val < q.val) {
    return root;
  }

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

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

  return root;
};

139. Word Break

dp를 이용하여 단어가 잘라내지면 dp내를 true로 바꾸어 단어가 wordDict의 배열로 분리되는지 확인하였습니다.

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

  for (let i = 1; i <= s.length; i++) {
    for (let word of wordDict) {
      if (i >= word.length && dp[i - word.length]) {
        const sub = s.slice(i - word.length, i);
        if (sub === word) {
          dp[i] = true;
          break;
        }
      }
    }
  }

  return dp[s.length];
};

150. Kth largest element in an Array

여러 로직을 사용하기 위해 Medium인지는 모르겠으나 그냥 sort후 -1만 접근해도 충분히 빨라 구현했습니다.

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findKthLargest = function (nums, k) {
  nums.sort((a, b) => b - a);

  return nums[k - 1];
};

@CitrusSoda CitrusSoda self-assigned this Nov 26, 2024
@oris8 oris8 requested review from wjsdncl and ynot0117 November 26, 2024 12:28
@oris8 oris8 merged commit 09d3cc6 into master Dec 2, 2024
3 checks passed
JooKangsan pushed a commit that referenced this pull request Dec 3, 2024
* 56 / Merge Intervals / Medium / 22m 31s

* 1584 / Min Cost to Connect All Points / Medium / >25m

* 235 / Lowest Common Ancestor of a Binary Search Tree / Medium / 13m 12s

* 139 / Word Break / Medium / 23m 19s

* 215 / Kth Largest Element in an Array / Medium / 2m
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