Skip to content

[jeongwoo903] Week 02 solutions #1230

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions 3sum/jeongwoo903.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* 투 포인터 방식 사용
* 시간 복잡도: O(n^2)
* 공간 복잡도; O(n^2)
*/

/**
* @param {number[]} nums
* @return {number[][]}
*/
const threeSum = (nums) => {
const sorted = [...nums].sort((a, b) => a - b);
const results = [];

sorted.forEach((val, i) => {
if (i > 0 && val === sorted[i - 1]) return;

let left = i + 1;
let right = sorted.length - 1;

while (left < right) {
const sum = val + sorted[left] + sorted[right];

if (sum === 0) {
results.push([val, sorted[left], sorted[right]]);

// 중복된 left/right 스킵
const currentLeft = sorted[left];
const currentRight = sorted[right];

while (left < right && sorted[left] === currentLeft) left++;
while (left < right && sorted[right] === currentRight) right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
});

return results;
};
20 changes: 20 additions & 0 deletions climbing-stairs/jeongwoo903.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* 시간 복잡도: O(n)
* 공간 복잡도: O(n)
*/

/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
if (n === 1) return 1;

const dp = [1, 2]

for (let i = 2; i < n; i++) {
dp[i] = dp[i-1] + dp[i-2]
}

return dp[n-1]
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드 자체는 깔끔하고 효율적으로 작성되었네요 👍
DP 배열을 구성하는 스타일에는 여러 가지가 있고
현재 코드는 dp[0]이 1번째 계단, dp[1]이 2번째 계단을 의미하는 방식으로 작성되었습니다.

또 다른 스타일로는 인덱스와 계단 번호를 일치시키는 방법도 많이 사용되는거같아 제안사항은 아니지만 공유드립니다.
:

var climbStairs = function(n) {
  const dp = [1, 1]; // dp[0]은 0번째(시작점), dp[1]은 1번째 계단
  
  for (let i = 2; i <= n; i++) {
    dp[i] = dp[i-1] + dp[i-2];
  }
  
  return dp[n];
};

이런 방식으로 하면 "dp[i]는 i번째 계단에 도달하는 방법의 수"라고 직관적으로 이해할 수 있어서 코드 가독성 면에서 장점이 있습니다. 물론 이건 단지 스타일의 차이일 뿐이고, 어느 쪽이든 문제 해결에는 차이가 없습니다.

두 방식 모두 많이 사용되는 패턴인거같아 공유드립니다.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로직에는 차이가 없어도 다음과 같이 바꿈으로써 설명과 가독성이 나아지는 것 같네요 ㅎㅎ
알려주셔서 감사합니다!

25 changes: 25 additions & 0 deletions product-of-array-except-self/jeongwoo903.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* 시간 복잡도: O(n)
* 공간 복잡도: O(n)
*/

/**
* @param {number[]} nums
* @return {number[]}
*/

var productExceptSelf = function(nums) {
const lefts = nums.reduce((products, num, i) => {
products.push(i === 0 ? 1 : products[i - 1] * nums[i - 1]);
return products;
}, []
);

return nums.reduceRight((result, num, i) => {
const rights = i === nums.length - 1 ? 1 : result.rightProduct * nums[i + 1];
result.products[i] *= rights;
result.rightProduct = rights;
return result;
}, { products: lefts, rights: 1 }
).products;
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

대부분의 풀이 아이디어가 비슷해서 reduce는 생각못했는데, 이런 접근법도 있군요!
reduce와 reduceRight를 활용해서 코드를 간결하게 작성한 점이 인상적입니다.
다만 처음 보는 사람이 이해하기에는 약간 복잡할 수 있겠다는 생각도 들었습니다.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

제가 가끔 함수형으로 짜본다고 다음과 같이 코드를 짰는데 조금 가독성이 나쁜 코드인 것 같다고 생각하긴 했습니다..ㅎㅎ
좋은 의견 감사합니다!

18 changes: 18 additions & 0 deletions valid-anagram/jeongwoo903.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* 시간 복잡도: O(n log n)
* 공간 복잡도: O(n)
*/

/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
if(s.length !== t.length) return false;

const strA = [...s].sort().join('');
const strB = [...t].sort().join('');

return strA === strB;
};
31 changes: 31 additions & 0 deletions validate-binary-search-tree/jeongwoo903.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* 시간 복잡도: O(n)
* 공간 복잡도; O(h)
* -> h는 트리의 높이
*/

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBST = function(root) {
function bst(node , min, max) {
if (!node) return true;

if (node.val <= min || node.val >= max) return false;

return (
bst(node.left, min, node.val) && helper(node.right, node.val, max)
);
}

return bst(root, -Infinity, Infinity);
};