Skip to content
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

[Sehwan]Week5 solutions with javascript #98

Merged
merged 4 commits into from
May 31, 2024
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
43 changes: 43 additions & 0 deletions 3sum/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
var threeSum = function (nums) {
// Sort nums array
const sortedNums = nums.sort((a, b) => a - b);
let result = [];

// Start iteration to pick first element for 3sum
for (let i = 0; i < sortedNums.length; i++) {
// Check if the first element is already greater than 0, no valid triplets possible after this point
if (sortedNums[i] > 0) {
break;
}

// Skip duplicates of the first element to avoid redundant triplets
if (i > 0 && sortedNums[i] === sortedNums[i - 1]) {
continue;
}

// Iterate to find sum of two pointer and nums[i]
let left = i + 1;
let right = sortedNums.length - 1;

while (left < right) {
let sum = sortedNums[i] + sortedNums[left] + sortedNums[right];

if (sum === 0) {
result.push([sortedNums[i], sortedNums[left], sortedNums[right]]);
// Skip duplicates of left and right pointers to avoid redundant triplets
while (sortedNums[left] === sortedNums[left + 1]) left++;
while (sortedNums[right] === sortedNums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
}
}
}
return result;
};

// TC: O(n^2)
// SC: O(n)
43 changes: 43 additions & 0 deletions encode-and-decode-strings/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class Solution {
/**
* @param {string[]} strs
* @returns {string}
*/
encode(strs) {
let result = "";
for (let str of strs) {
result += str.length.toString() + "#" + str;
}
return result;
}

/**
* @param {string} str
* @returns {string[]}
*/
decode(str) {
let result = [];
let i = 0;

while (i < str.length) {
// Find the position of the next '#'
let j = i;
while (str[j] !== "#") {
j++;
}

// Length of the next string
const len = parseInt(str.slice(i, j));
i = j + 1; // Move past the '#'

// Extract the string of length 'len'
result.push(str.slice(i, i + len));
i += len; // Move past the extracted string
}

return result;
}
}

// TC: O(n),O(n)
// SC: O(n),O(n)
30 changes: 30 additions & 0 deletions longest-consecutive-sequence/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
var longestConsecutive = function (nums) {
// Return 0 if there are no elements in nums
if (nums.length === 0) return 0;
Copy link
Contributor

Choose a reason for hiding this comment

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

저는 이렇게 앞에 예외 처리해주는 걸 생각하지 않았는데 이렇게 미리 걸러내주는게 효율적이겠군요.


// Create a set to find values efficiently
const numSet = new Set(nums);
let maxLength = 0;

for (let num of numSet) {
// Check if this is the start of a sequence
if (!numSet.has(num - 1)) {
let currentNum = num;
let currentLength = 1;

// Count the length of the sequence
while (numSet.has(currentNum + 1)) {
currentNum += 1;
currentLength += 1;
}

// Update the maximum length
maxLength = Math.max(maxLength, currentLength);
}
}

return maxLength;
};

// TC: O(n)
// SC: O(n)
40 changes: 40 additions & 0 deletions product-of-array-except-self/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function (nums) {
const len = nums.length;
const lastIndex = len - 1;

// Declare prefix, postfix array
let prefix = new Array(len).fill(1);
let postfix = new Array(len).fill(1);

// Iterate loop to add prefix[i-1]*nums[i] values into prefix array
prefix[0] = nums[0];
for (let i = 1; i < nums.length; i++) {
prefix[i] = prefix[i - 1] * nums[i];
}

// Iterate loop to add postfix[i]*nums[i-1] values into postfix array
postfix[lastIndex] = nums[lastIndex];
for (let i = lastIndex; i >= 1; i--) {
postfix[i - 1] = postfix[i] * nums[i - 1];
}

// Make output array with prefix and postfix arrays
let output = new Array(len).fill(1);

// First index value is equal to postfix[1]
output[0] = postfix[1];
// Last index value is equal to prefix[lastIndex-1]
output[lastIndex] = prefix[lastIndex - 1];
for (let i = 1; i < len - 1; i++) {
output[i] = prefix[i - 1] * postfix[i + 1];
}

return output;
};

// TC: O(n)
// SC: O(n)
14 changes: 14 additions & 0 deletions top-k-frequent-elements/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
var topKFrequent = function (nums, k) {
// 1. Hashmap { num : frequency }
let map = {};

// 2. Iterate counts frequency of each value
for (num of nums) {
// Check there is already num key or not
if (!map[num]) map[num] = 0;
map[num]++;
}

// 3. Sort frequency and return sliced array
return [...Object.keys(map)].sort((a, b) => map[b] - map[a]).slice(0, k);
Copy link
Contributor

@DaleSeo DaleSeo May 28, 2024

Choose a reason for hiding this comment

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

Cool! 😝

Copy link
Contributor

Choose a reason for hiding this comment

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

object 앞에 ...은 뭘 의미할까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

자바스크립트에서 '...'은 spread operator로 context에 따라 다양하게 사용되곤 하는데요.
여기서는 map 오브젝트의 key들을 어레이로 받을 때 shallow copy를 하기 위해서 사용했습니다.
spread operator 없이 아래와 같은 코드로 실행해도 문제는 없는데,

return (Object.keys(map).sort((a,b)=>map[b]-map[a]).slice(0,k))

원본 오브젝트를 변경하지 않고 리턴값을 받아야 하는 상황을 가정했다고 보시면 될 것 같습니다.

Copy link
Contributor

@SamTheKorean SamTheKorean May 30, 2024

Choose a reason for hiding this comment

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

더 안전하게 실행하려고 사용하신 거군요~! 친절한 설명감사드립니다! 덕분에 자바스크립트도 배웁니다!

};