diff --git a/javascript/LeetCode/Array/1725.js b/javascript/LeetCode/Array/1725.js new file mode 100644 index 0000000..e447371 --- /dev/null +++ b/javascript/LeetCode/Array/1725.js @@ -0,0 +1,46 @@ +/** + * 1725. Number Of Rectangles That Can Form The Largest Square + * + * @param {number[][]} rectangles + * @return {number} + */ +var countGoodRectangles = function(rectangles) { + /** + * 2維陣列,每個陣列元素分別代表該陣列三角形的長l、寬w + * each rectangle are of lengths [5,3,5,5] is min of [l,w] + * 回傳有幾個maxLen可組成三角形 + */ + // solution 1 + // let rectangleLen = []; + // let countMaxLen = 0; + // for(const eachLen of rectangles){ + // rectangleLen.push(parseInt(Math.min(...eachLen))); + // } + // let maxLen = Math.max(...rectangleLen); + // for(let i = 0;i < rectangleLen.length;++i) { + // if(rectangleLen[i] === maxLen){ + // countMaxLen++; + // } + // } + // return countMaxLen; + + // solution 2. + // time:O(N) + let count = 0, maxLen = 0; + for(const eachLen of rectangles) { + let side = Math.min(...eachLen); + + if(side > maxLen){ + count = 1; + maxLen = side; + }else if(side === maxLen){ + count++; + } + } + return count; +}; +let rectangles = [[5,8],[3,9],[5,12],[16,5]] +// Output: 3 +// Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5]. +// The largest possible square is of length 5, and you can get it out of 3 rectangles. +console.log(countGoodRectangles(rectangles)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/1848.js b/javascript/LeetCode/Array/1848.js new file mode 100644 index 0000000..8c23b26 --- /dev/null +++ b/javascript/LeetCode/Array/1848.js @@ -0,0 +1,27 @@ +/** + * 1848. Minimum Distance to the Target Element + * + * @param {number[]} nums + * @param {number} target + * @param {number} start + * @return {number} + */ +var getMinDistance = function(nums, target, start) { + /** + * nums[i] === target + * 找最小的abs(i - start) + */ + let minDistance = Infinity; + for(let i = 0;i < nums.length;++i) { + if(nums[i] === target){ + minDistance = Math.min(minDistance,Math.abs(i - start)); + } + } + return minDistance; +}; +// let nums = [1,2,3,4,5], target = 5, start = 3 +// Output: 1 +// Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. +let nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 9; +// 0 +console.log(getMinDistance(nums,target,start)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/2515.js b/javascript/LeetCode/Array/2515.js new file mode 100644 index 0000000..05acc0a --- /dev/null +++ b/javascript/LeetCode/Array/2515.js @@ -0,0 +1,38 @@ +/** + * 2515. Shortest Distance to Target String in a Circular Array + * + * 陣列是一個圓,意味著陣列頭元素可以取得陣列尾元素 + * 從左邊或右邊開始都能通 + * + * @param {string[]} words + * @param {string} target + * @param {number} startIndex + * @return {number} + */ +var closestTarget = function(words, target, startIndex) { + /** + * 若陣列中沒有元素符合target,回傳-1 + * 往左或往右找 + * 回傳最短能到words[target]的距離 + */ + for(let i = 0;i < words.length;++i) { + let right = (startIndex + i) % words.length; + let left = (startIndex - i + words.length) % words.length; + + if(words[left] === target || words[right] === target){ + return i; + } + } + return -1; +}; +let word = ["hello","i","am","leetcode","hello"], target = "hello", startIndex = 1 +/* +Output: 1 +Explanation: We start from index 1 and can reach "hello" by +- moving 3 units to the right to reach index 4. +- moving 2 units to the left to reach index 4. +- moving 4 units to the right to reach index 0. +- moving 1 unit to the left to reach index 0. +The shortest distance to reach "hello" is 1. +*/ +console.log(closestTarget(word,target,startIndex)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/3740.js b/javascript/LeetCode/Array/3740.js new file mode 100644 index 0000000..0d771cc --- /dev/null +++ b/javascript/LeetCode/Array/3740.js @@ -0,0 +1,40 @@ +/** + * 3740. Minimum Distance Between Three Equal Elements I + * + * @param {number[]} nums + * @return {number} + */ +var minimumDistance = function(nums) { + /** + * good定義:nums[i] == nums[j] == nums[k]. + * 其中(i, j, k)是3個不重複index且元素一樣 + * distance of a good tuple is abs(i - j) + abs(j - k) + abs(k - i), where abs(x) denotes the absolute value of x. + * 回傳最小good tuple,否則-1 + * + * 必須要有3個元素是一樣的 + */ + let ans = Infinity; + if(nums.length < 2){ + return -1; + } + for(let i = 0;i < nums.length;++i) { + for(let j = i+1;j < nums.length;++j) { + if(nums[i] === nums[j]){ + for(let k = j+1;k < nums.length;++k) { + if(nums[j] === nums[k]){ + ans = Math.min(ans,2*(k-i)); + } + } + } + } + } + return ans === Infinity ? -1 : ans; +}; +let nums = [1,1,2,3,2,1,2] +/* +Output: 8 +Explanation: +The minimum distance is achieved by the good tuple (2, 4, 6). +(2, 4, 6) is a good tuple because nums[2] == nums[4] == nums[6] == 2. Its distance is abs(2 - 4) + abs(4 - 6) + abs(6 - 2) = 2 + 2 + 4 = 8. +*/ +console.log(minimumDistance(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/3761.js b/javascript/LeetCode/Array/3761.js new file mode 100644 index 0000000..5eecd02 --- /dev/null +++ b/javascript/LeetCode/Array/3761.js @@ -0,0 +1,44 @@ +/** + * 3761. Minimum Absolute Distance Between Mirror Pairs + * + * mirror pair = indices(i,j) + * reverse(nums[i] === nums[j]) 若數字前面為0,則省略0 + * 回傳最小mirror pair絕對距離 abs(i - j),若無,回傳-1 + * + * @param {number[]} nums + * @return {number} + */ +var minMirrorPairDistance = function(nums) { + /** + * 陣列元素兩個為一組(i,j),每個元素反轉後跟下一個元素比較是否一致。若一致 abs(index i - index j),取最小結果 + */ + // 反轉數字 + function reverseNum(x){ + let y = 0; + while(x > 0){ + y = y * 10 + (x % 10); + x = Math.floor(x / 10); + } + return y; + } + + let map = new Map(); + let ans = nums.length + 1; + for(let i = 0;i < nums.length;i++){ + if(map.has(nums[i])){ + ans = Math.min(ans,i - map.get(nums[i])); + } + map.set(reverseNum(nums[i]),i); + } + return ans === nums.length + 1 ? -1 : ans; +}; +let nums = [12,21,45,33,54] +/* +Output: 1 +Explanation: +The mirror pairs are: +(0, 1) since reverse(nums[0]) = reverse(12) = 21 = nums[1], giving an absolute distance abs(0 - 1) = 1. +(2, 4) since reverse(nums[2]) = reverse(45) = 54 = nums[4], giving an absolute distance abs(2 - 4) = 2. +The minimum absolute distance among all pairs is 1. +*/ +console.log(minMirrorPairDistance(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/String/3794.js b/javascript/LeetCode/String/3794.js index 522b84f..d769987 100644 --- a/javascript/LeetCode/String/3794.js +++ b/javascript/LeetCode/String/3794.js @@ -7,7 +7,26 @@ * @return {string} */ var reversePrefix = function(s, k) { - return s.substring(0,k).split("").reverse().join("") + s.substring(k); + // solution 1. + // return s.substring(0,k).split("").reverse().join("") + s.substring(k); + + // solution 2. + // 2 pointers + let result = ""; + let i = 0,j = k - 1; // left side and right side + let splitS = s.split(""); + while(i < j){ + let letter = splitS[i]; + // swap + splitS[i] = splitS[j]; + splitS[j] = letter; + i++; + j--; + } + for (let a = 0; a < splitS.length; a++) { + result += splitS[a]; + } + return result; }; // let s = "abcd", k = 2; // "bacd" diff --git a/javascript/index.js b/javascript/index.js index db0c900..8ac6da1 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1313,6 +1313,201 @@ var findAndReplacePattern = function(words, pattern) { } }; -let word = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"; +// let word = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"; // ["mee","aqq"] -// console.log(findAndReplacePattern(word,pattern)); \ No newline at end of file +// console.log(findAndReplacePattern(word,pattern)); + +/** + * 657. Robot Return to Origin + * + * @param {string} moves + * @return {boolean} + */ +var judgeCircle = function(moves) { + /** + * moves只會有'R' (right), 'L' (left), 'U' (up)和'D' (down)這幾個英文字母 + * 回傳布林看moves後是否會回到原點(0, 0) + * + * x(0),y(0) + * u = d + * r = l + * + * 計算每個字母出現次數,r的出現次數 = l的出現次數; u 的出現次數 = d的出現次數 + */ + // solution 1. + // TC:O(N) + // let direactionsCount = new Map(); + // for(let i = 0;i < moves.length;++i) { + // direactionsCount.has(moves[i]) ? direactionsCount.set(moves[i],direactionsCount.get(moves[i])+1) : direactionsCount.set(moves[i],1); + // } + // // 取得Map.get(key)對應value + // if(direactionsCount.get("U") === direactionsCount.get("D") && direactionsCount.get("R") === direactionsCount.get("L")){ + // return true; + // } + // return false; + + // this solution? + let direactionsObj = {}; + for(let i = 0;i < moves.length;++i) { + if(Object.hasOwn(direactionsObj, moves[i])){ + direactionsObj[moves[i]] +=1; + }else{ + direactionsObj[moves[i]] = 1; + } + } + console.log(direactionsObj) + + // solution 2. + // TC: O(N) + // 計算x和y各自出現次數 + // x = 水平(左l右r); y = 垂直(上u下d) + // 水平(x): + // L:x--; R:x++; + // 垂直(y): + // U:y++ ; D: y-- + // let x = 0,y = 0; + // for(let i = 0;i < moves.length;++i) { + // if(moves[i] === 'R'){ + // x++; + // }else if(moves[i] === 'U'){ + // y++; + // }else if(moves[i] === 'L'){ + // x-- + // }else if(moves[i] === 'D'){ + // y--; + // } + // } + // return x === 0 && y === 0; + +}; +let moves = "UD"; +/* +Output: true +Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. +*/ +// let moves = "LL"; +/* +Output: false +Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves. +*/ +// console.log(judgeCircle(moves)); + +/** + * 3663. Find The Least Frequent Digit + * + * 參數為一整數n,找出在其十進位表示中出現頻率最低的數字。如果多個數字的出現頻率相同,則選擇最小的元素。 + * 數字x的出現頻率是指它在n的十進位表示法中的出現次數 + * + * @param {number} n + * @return {number} + */ +var getLeastFrequentDigit = function(n) { + /** + * 依據每個數字出現的次數找出出現次數最少的元素,若有好幾個數字出現次數相同,回傳最小的那個元素。 + * + * solution 1. Hash table + * solution 2. Array + */ + + // solution 1. + // Hash table + // let nSplitToStr = n.toString().split(""); + // let map = new Map(); + // let minFreq = Infinity,result = 10; + // for(let i = 0;i < nSplitToStr.length;++i) { + // map.has(nSplitToStr[i]) ? map.set(nSplitToStr[i],map.get(nSplitToStr[i]) + 1) : map.set(nSplitToStr[i],1); + // } + // 不斷比較minFreq和value哪個最小,因此minFreq值會一直更新 + // for(const [key,value] of map){ + // minFreq = Math.min(minFreq,value); + // } + // for(const [key,value] of map){ + // // 最小的value = minFreq + // if(value === minFreq){ + // // 比較result和key哪個最小,key = 元素 + // result = Math.min(result,key); + // } + // } + // return reuslt; + + // solution 2. + // Array. + let hash = new Array(10).fill(0); + let ans = 0,minFreq = 0; + console.log(hash) + +}; +let n = 723344511; +/* +Output: 2 +Explanation: +The least frequent digits in n are 7, 2, and 5; each appears only once. +*/ +// console.log(getLeastFrequentDigit(n)); + +/** + * 3488. Closest Equal Element Queries + * + * 2 array: + * queries. + * circular array: nums. + + * min distance between the element at index queries[i] and any other index j: nums[j] === nums[queries[i]] + * same size aas queries where answer[i] + * @param {number[]} nums + * @param {number[]} queries + * @return {number[]} + */ +var solveQueries = function(nums, queries) { + /** + * querise[i] = nums[i] + * + * Use a HashMap to store the indices of each number in nums. The key should be nums[i], and the value should be a list of indices where nums[i] appears. + * Hint 2: For each query, retrieve the stored list of indices for nums[queries[i]]. + * Hint 3: Use binary search to efficiently find the next occurrence of the number. This reduces the lookup time to O(log N) instead of O(N). + * + */ + let mapNums = new Map(); + for(let i = 0;i < nums.length;++i) { + // mapNums: key(nums[i]),value(i) + if(!mapNums.has(nums[i])) { + mapNums.set(nums[i], []) + } + mapNums.get(nums[i]).push(i) + } + console.log(mapNums) + let arr = new Array(nums.length).fill(-1); + // for(let i = 0;i < queries.length;++i) { + // if(mapNums.has(queries[i])){ + // console.log(mapNums.get(queries[i])) + // } + // } + // binary search + function binarySearch(arr,target){ + let left = 0,right = arr.length - 1; + while(left <= right){ + let mid = left + Math.floor((right - left) / 2); + + if(arr[mid] === target){ + return mid; + }else if(arr[mid] > target){ + right--; + }else{ + left++; + } + } + return -1; + } + +}; +let nums = [1,3,1,4,1,3,2], queries = [0,3,5]; +/* +Output: [2,-1,3] +Explanation: +Query 0: The element at queries[0] = 0 is nums[0] = 1. The nearest index with the same value is 2, and the distance between them is 2. +Query 1: The element at queries[1] = 3 is nums[3] = 4. No other index contains 4, so the result is -1. +Query 2: The element at queries[2] = 5 is nums[5] = 3. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: 5 -> 6 -> 0 -> 1). +*/ +// console.log(solveQueries(nums,queries)); + +