-
Notifications
You must be signed in to change notification settings - Fork 126
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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) |
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) |
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; | ||
|
||
// 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) |
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) |
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Cool! 😝 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. object 앞에 ...은 뭘 의미할까요? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 자바스크립트에서 '...'은 spread operator로 context에 따라 다양하게 사용되곤 하는데요. return (Object.keys(map).sort((a,b)=>map[b]-map[a]).slice(0,k)) 원본 오브젝트를 변경하지 않고 리턴값을 받아야 하는 상황을 가정했다고 보시면 될 것 같습니다. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 더 안전하게 실행하려고 사용하신 거군요~! 친절한 설명감사드립니다! 덕분에 자바스크립트도 배웁니다! |
||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저는 이렇게 앞에 예외 처리해주는 걸 생각하지 않았는데 이렇게 미리 걸러내주는게 효율적이겠군요.