본문 바로가기

Algorithm

(38)
[LeetCode] Delete Node in a Linked List (js/연결 리스트) 문제 : There is a singly-linked list head and we want to delete a node node in it. You are given the node to be deleted node. You will not be given access to the first node of head. All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it fro..
[LeetCode] Reverse String 문제 : Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. - 주어진 문자형 배열 s를 수정하여 return (in-place) - O(1)의 시간복잡도를 가진 추가 메모리만을 활용하여 풀기 *O(1) - 일정한 복잡도(constant complexity) : 입력값이 증가하더라도 시간이 늘어나지 않는다. 풀이 : /** * @param {character[]} s * @return {void} Do not return anything, modi..
[LeetCode] Single Number (Map()을 활용해 풀기) 문제 : Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. 주어진 integer 배열 nums에는 단 하나를 제외하고 모든 숫자가 2번씩 등장한다. 한 번만 나타나는 숫자를 찾아라. 반드시 선형 복잡도와 추가 공간 사용없이 문제를 해결해야한다. * 선형복잡도(linear runtime complexity) : 입력값과 시간이 같은 비율로 증가 O(n) 풀이 : /** * @param {num..
[LeetCode] Contains Duplicate (3가지 풀이방법) 문제 : 배열 nums의 숫자들 중 하나라도 중복이 있는 경우 true를 return. 중복 여부만 판단하면 되는 문제라 Set()을 활용해 풀기로했다. 풀이 : /** * @param {number[]} nums * @return {boolean} */ const containsDuplicate = function(nums) { const newArr = [...new Set(nums)]; return !(newArr.length == nums.length); }; Runtime: 81 ms Memory Usage: 56.6 MB nums의 중복을 제거한 newArr를 만들어 두 배열의 길이를 비교해준다. 정답은 바로 맞췄지만, runtime이 생각보다 더 나와서 다른 방법으로 풀어보기로 풀이 2 : ..
[LeetCode]Best Time to Buy and Sell Stock II 언제쯤 다른 사람의 풀이에서 힌트를 얻지 않고 문제를 풀 수 있을까. 문제 : 이번 문제의 key point는 1. 주식을 당일 사고 팔 수 있다. 2. 꼭 한 번만 팔아서 이윤(profit)을 남길 필요가 없다. (다음날보다 1원이라도 저렴하면 사서 판다) 풀이 : /** * @param {number[]} prices * @return {number} */ var maxProfit = function(prices) { var cheapDay = prices.indexOf(Math.min(...prices)); var lastIdx = prices.length; var availableDay = prices.slice(cheapDay,lastIdx) var expensiveDay = prices.ind..
[LeetCode]Remove Duplicates from Sorted Array (Splice, Set 활용) 코딩테스트를 기탄수학처럼 매일 꾸준히 푸는 개발자가 되고 싶지만, 마음처럼 쉽지 않다. (생각해보면, 기탄수학도 그렇게 꾸준히 푸는 학생은 아니었음 ㅎ) 문제 : 풀이 : const removeDuplicates = (nums) => { let newArr = [...new Set(nums)]; return newArr; }; 처음에는 단순 중복 제거문제라고 생각해서 Set()을 사용해 문제를 풀었다. 아무 것도 출력이 안된다. 콘솔로도 찍어보고 한참을 빙빙 돌다가 문제를 다시 보니 in-place 가 눈에 띈다. 최초에 Param으로 주어지는 nums 내에서 값을 수정해야 한다. 새로운 변수를 할당하지 않고 어떻게 풀 수 있을까. for문을 돌리는 방법이 있겠으나, 그게 더 어렵게 느껴지고 어떻게 Se..
[coderbyte/js] First Reverse 문제 : Have the function FirstReverse(str) take the str parameter being passed and return the string in reversed order. For example: if the input string is "Hello World and Coders" then your program should return the string sredoC dna dlroW olleH. 풀이방법 : 1. str로 들어오는 string 값을 쪼개서 배열에 담는다 2. 배열을 역순으로 3. join('')으로 배열에서 string으로 변환 처음에 str을 쪼개서 배열에 담고 나면 for문을 돌려서 역순으로 다시 배열에 담아서 출력을 해볼까 생각했었는데 이런 ..
[coderbyte/js] First Factorial 문제 : Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24. For the test cases, the range will be between 1 and 18 and the input will always be an integer. function FirstFactorial(num) { let sum = 1; for (i = num; i > 0; i--) { sum = sum * i; } return sum; } // keep t..