LeetCode > 2208 Minimum Operations to Halve Array Sum
·
🔒Algorithm
📌링크https://leetcode.com/problems/minimum-operations-to-halve-array-sum/description/🔨풀이이 문제의 조건을 보면 단순히 정렬을 이용해서 풀면 시간초과가 날 것이라고 생각되어 우선순위 큐를 이용하여 연산횟수를 최적화 하였다. 우선순위 큐를 구현하기 위해 힙(완전이진 트리) 자료구조를 이용하였고 우선순위 큐에서 가장 큰 값을 반으로 나누면서 계산횟수를 카운팅 하여 문제를 풀 수 있었다. 해당 문제의 시간복잡도는 O( n log n ) 이다. ( 시간복잡도 관례대로 log의 밑은 생략 )  /** * @param {number[]} nums * @return {number} */var halveArray = function (nums) { ..
LeetCode > 1346. Check If N and Its Double Exist
·
🔒Algorithm
문제https://leetcode.com/problems/check-if-n-and-its-double-exist/풀이쉽게 풀 수 있다. 시간 복잡도는 O(n^2) 이다./** * @param {number[]} arr * @return {boolean} */var checkIfExist = function(arr) { for(let i =0; i
LRU ( Least Recently Used ) 알고리즘 구현해보기
·
⭐FE
📌LRU 알고리즘LRU(Least Recently Used) 알고리즘은 가장 오랫동안 사용되지 않은 데이터를 제거하는 전략이다. 캐시 교체 방식으로 많이 쓰인다. 해당 알고리즘은 hash 와 double linked list 를 이용하여 구현할 수 있다. 📌실제로 구현해봤다.자바스크립트로 구현해봤다. hash table은 Map 객체를 이용했으며 Map에는 각 key에 대응되는 node가 저장되어 있다. ( 각 노드의 prev, next 는 이전,다음 노드를 카리킨다 )   // LRU cache 교체 알고리즘 구현 (has table + double linked list이용 )class Node { constructor(key, value) { this.key = key; ..
LeetCode [JS] > Third Maximum Number
·
🔒Algorithm
✅문제https://leetcode.com/problems/third-maximum-number/description/✅풀이Set으로 중복제거하고 시작하면 편하게 구할 수 있다. 시간복잡도는 O(NlogN) 으로 이런 이유는 js sorting algorithm 이 tim sort 방식을 사용하기 때문이다. 참고로 tim sort 방식은 merge sort 와 insertion sort를 결합하여 만든 sorting 방식이라고 한다. 자세히 알고 싶으면 https://d2.naver.com/helloworld/0315536 를 보면 된다./** * @param {number[]} nums * @return {number} */var thirdMax = function (nums) { const so..
HackerRank > big-sorting
·
🔒Algorithm
➕문제링크https://www.hackerrank.com/challenges/big-sorting/problem?isFullScreen=true💡문제풀이문자의 길이가 다를경우 각 자릿수를 비교하는 형태로 수의 대소를 비교하면서 정렬했다."use strict";const fs = require("fs");process.stdin.resume();process.stdin.setEncoding("utf-8");let inputString = "";let currentLine = 0;process.stdin.on("data", function (inputStdin) { inputString += inputStdin;});process.stdin.on("end", function () { inputS..
LeetCode[JS] > 2718. Sum of Matrix After Queries
·
🔒Algorithm
문제링크https://leetcode.com/problems/sum-of-matrix-after-queries/description/문제풀이이 문제를 아무 생각없이 순서대로 구현하여 답을 도출 시 memory heap size 초과를 맞딱드리게 된다. 2차원 배열을 만들어 해당 배열을 조작하는 대신 나는 Set 객체를 이용하여 연산횟수를 최소화 하였다. 뒤에 있는 쿼리일수록 기존 배열의 값을 override 하기 때문에 맨뒤의 쿼리부터 순회하면서 값을 계산하면 된다. /** * @param {number} n * @param {number[][]} queries * @return {number} */var matrixSumQueries = function (n, queries) { let sum =..
LeetCode [JS] > 3192. Minimum Operations to Make Binary Array Elements Equal to One II
·
🔒Algorithm
💡문제링크https://leetcode.com/problems/minimum-operations-to-make-binary-array-elements-equal-to-one-ii/🔨문제풀이큰 어려움 없이 풀 수 있었다. 원래는 flipped이라는 값을 이용하지 않고 cnt를 증가시키면서 for of 문 내부에서 cnt%2===0일때 1일때 각각 분기 처리했지만 그걸 flipped 이라는 boolean 값으로 변경해서 연산과정을 빼니 run-time 속도가 향상 되었다. /** * @param {number[]} nums * @return {number} */var minOperations = function(nums) { let flipped = false let cnt = 0 ..
LeetCode[JS] 53번 Maximum Subarray
·
🔒Algorithm
💡문제링크https://leetcode.com/problems/maximum-subarray/description/🔨풀이처음에 dp로 풀어야 되나 하면서 접근했던거 같은데 한참을 뚫어져라 처다보니 규칙성을 찾을 수 있었다. nums 배열을 순회하면서 max값을 갱신하고 만약 다음 수를 더했을 때 0이하이면 여태 더한 sum값을 초기화하면 된다.  /** * @param {number[]} nums * @return {number} */var maxSubArray = function(nums) { let max = nums[0] let sum = nums[0] let length = nums.length for(let i=1; i
백준[JS] > 1697번 숨바꼭질
·
🔒Algorithm
➕문제링크https://www.acmicpc.net/problem/1697🔨문제풀이bfs를 이용하돼 불필요한 연산은 처리하지 않는 방향으로 최적화 하였다. ( dp[ i ] 는 i지점을 가는 데 걸리는 최소시간 )let fs = require("fs");let input = fs.readFileSync("/dev/stdin").toString().trim();let [N, K] = input.split(" ").map((n) => Number(n));let dp = Array(100001).fill(Infinity);let endPoint = 100000;let index = N;let answer = undefined;dp[N] = 0;let queue = [[N, 0]];while (queue.le..
10진수 <-> 16진수 변환 알고리즘
·
🔒Algorithm
🔥배경알고리즘 문제를 풀다보면 진수처리 해야되는 경우가 생긴다. 대표적인 예시로 10진수와 16진수간 변환문제가 있다. 해당 알고리즘을 작성해 보았다. ( 혹여나 해당 알고리즘이 틀렸을 경우 지적해주시면 감사해요 ) ✅코드let dictionary = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15, 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f",};// 16진수를 10진수로 변환 하면?const hexT..