Skip to content

Conversation

@Berrnuda
Copy link
Contributor

@Berrnuda Berrnuda commented Dec 3, 2024

📌 푼 문제

문제이름 문제링크
Reverse integer https://leetcode.com/problems/reverse-integer
Network Delay Time https://leetcode.com/problems/network-delay-time
Combination Sum https://leetcode.com/problems/combination-sum
Detect Squares https://leetcode.com/problems/detect-squares
Insert Interval https://leetcode.com/problems/insert-interval

📝 간단한 풀이 과정

7 Reverse integer

x를 문자형으로 바꾸고 한글자식 나눠서 자른뒤 reverse 시키고 다시 숫자형으로 바꾸는 방식입니다.
sign이란 변수에 양수인지 음수인지 담아두고 Math.pow 메소드로 32비트 확인을 하는 코드입니다.

var reverse = function (x) {
  const sign = x < 0;
  const rev = parseInt(String(Math.abs(x)).split("").reverse().join(""));

  if (rev < -Math.pow(2, 31) || rev > Math.pow(2, 31) - 1) return 0;

  return sign ? -rev : rev;
};

743 Network Delay Time

힙을 사용하지 않고 풀어봤습니다.
times를 리스트 형태로 저장하고 dist변수로 시작 노드의 거리를 설정한 뒤
방문하지 않은 노드중에서 최소거리의 노드를 찾고 방문처리한 다음 그 노드와 연결된 노드의 거리를 갱신하는 코드입니다.

var networkDelayTime = function (times, n, k) {
  const node = Array.from({ length: n + 1 }, () => []);
  for (const [u, v, w] of times) node[u].push([v, w]);

  const dist = new Array(n + 1).fill(Infinity);
  dist[k] = 0;

  const visited = new Array(n + 1).fill(false);

  for (let i = 1; i <= n; i++) {
    let minNode = -1;
    for (let j = 1; j <= n; j++) {
      if (!visited[j] && (minNode === -1 || dist[j] < dist[minNode]))
        minNode = j;
    }

    if (dist[minNode] === Infinity) break;

    visited[minNode] = true;

    for (const [neighbor, weight] of node[minNode]) {
      const newDist = dist[minNode] + weight;
      if (newDist < dist[neighbor]) dist[neighbor] = newDist;
    }
  }

  const maxDist = Math.max(...dist.slice(1));
  return maxDist === Infinity ? -1 : maxDist;
};

39 Combination Sum

솔루션 보니 재귀함수 방식으로 푼게 좀 많아서 따라 풀어보려다 뭔가 머리아파서 그냥 반복문으로 구현해봤습니다.
조합, 합, 시작 인덱스를 저장해둘 스택을 선언하고 target과 비교해가며 다음 후보를 탐색하는 반복문입니다.

var combinationSum = function (candidates, target) {
  const result = [];
  const stack = [[[], 0, 0]];

  while (stack.length > 0) {
    const [currentCombination, currentSum, startIndex] = stack.pop();

    if (currentSum === target) {
      result.push(currentCombination);
      continue;
    }

    if (currentSum > target) continue;

    for (let i = startIndex; i < candidates.length; i++) {
      stack.push([
        [...currentCombination, candidates[i]],
        currentSum + candidates[i],
        i,
      ]);
    }
  }

  return result;
};

2013 Detect Squares

add 메서드는 / 을 문자열 키로 잡고 ptsCount라는 배열에 추가하는 메서드입니다.
count 메서드는 저장된 p을 순회하며 q와 정사각형을 만들수 있는지 확인하는 메서드입니다.

var DetectSquares = function () {
  this.ptsCount = new Map();
};

/**
 * @param {number[]} point
 * @return {void}
 */
DetectSquares.prototype.add = function (point) {
  const key = `${point[0]}/${point[1]}`;
  this.ptsCount.set(key, (this.ptsCount.get(key) || 0) + 1);
};

/**
 * @param {number[]} point
 * @return {number}
 */
DetectSquares.prototype.count = function (point) {
  const [qx, qy] = point;
  let result = 0;

  for (const key of this.ptsCount.keys()) {
    const [px, py] = key.split("/").map(Number);

    if (Math.abs(px - qx) === Math.abs(py - qy) && px !== qx && py !== qy) {
      const key1 = `${px}/${qy}`;
      const key2 = `${qx}/${py}`;
      result +=
        (this.ptsCount.get(key) || 0) *
        (this.ptsCount.get(key1) || 0) *
        (this.ptsCount.get(key2) || 0);
    }
  }

  return result;
};

57 Insert Interval

기존 배열에 새 구간을 추가한뒤 시작시간을 기준으로 정렬하고 res라는 변수에 결과배열을 저장하고 첫번째 구간을 추가해둡니다.
그리고 intervals 배열을 순회하면서 조건문을 통해 겹치면 업데이트하는 반복문 입니다.

var insert = function (intervals, newInterval) {
  intervals.push(newInterval);
  intervals.sort((a, b) => a[0] - b[0]);

  let res = [intervals[0]];

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

  return res;
};

@oris8 oris8 requested review from oh-chaeyeon and wch2208 December 3, 2024 12:40
@oris8 oris8 merged commit 08c504a into master Dec 10, 2024
3 checks passed
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