diff --git a/javascript/LeetCode/Array/1534.js b/javascript/LeetCode/Array/1534.js new file mode 100644 index 0000000..a5d977c --- /dev/null +++ b/javascript/LeetCode/Array/1534.js @@ -0,0 +1,32 @@ +/** + * 1534. Count Good Triplets + * + * good triplets: + * 0 <= i < j < k < arr.length + * |arr[i] - arr[j]| <= a + * |arr[j] - arr[k]| <= b + * |arr[i] - arr[k]| <= c + * + * @param {number[]} arr + * @param {number} a + * @param {number} b + * @param {number} c + * @return {number} + */ +var countGoodTriplets = function(arr, a, b, c) { + let ans = 0; + for(let i = 0;i < arr.length;i++) { + for(let j = i+1;j < arr.length;j++) { + for(let k = j+1;k < arr.length;k++) { + if(Math.abs(arr[i] - arr[j]) <= a && Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c){ + ans++; + } + } + } + } + return ans; +}; +let arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3; +// Output: 4 +// Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)]. +console.log(countGoodTriplets(arr,a,b,c)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/1913.js b/javascript/LeetCode/Array/1913.js index 8dc6259..982c7e9 100644 --- a/javascript/LeetCode/Array/1913.js +++ b/javascript/LeetCode/Array/1913.js @@ -48,9 +48,20 @@ var maxProductDifference = function (nums) { // return (max[0] * max[1]) - (min[0] * min[1]); // solution 2.Runtime took 100 ms - nums.sort((a, b) => a - b); - let length = nums.length; - return (nums[length - 1] * nums[length - 2]) - (nums[0] * nums[1]); + // nums.sort((a, b) => a - b); + // let length = nums.length; + // return (nums[length - 1] * nums[length - 2]) - (nums[0] * nums[1]); + + + // solution 3.Update in 2025/10/2.Runtime took 73 ms. + // pair a = 兩個最大數; pair b = 兩個最小數 + // sort 由大至小 + nums.sort((a,b) => b - a); + // 取得第一組兩個最大數並相乘 + let pairA = nums.slice(0,2).reduce((acc, curr) => acc * curr, 1); + // 取得最後面兩個最小數並相乘 + let pairB = nums.slice(nums.length - 2,nums.length).reduce((acc, curr) => acc * curr, 1); + return Math.abs(pairA - pairB); }; const nums = [5, 6, 2, 7, 4]; // 34 => (6*7)-(2*4)=34 diff --git a/javascript/LeetCode/Array/2169.js b/javascript/LeetCode/Array/2169.js new file mode 100644 index 0000000..c32c2c4 --- /dev/null +++ b/javascript/LeetCode/Array/2169.js @@ -0,0 +1,42 @@ +/** + * 2169. Count Operations to Obtain Zero + * + * 一次操作中,若nums1 > nums2,則nums1 = nums1 - nums2 + * nums1 < nums2, nums2 = nums1 - nums2 + * 計算要幾次才能使得nums1 = 0 or num2 = 0 + * + * @param {number} num1 + * @param {number} num2 + * @return {number} + */ +var countOperations = function(num1, num2) { + // solution 1. + // let ans = 0; + // while(num1 !== 0 && num2 !== 0){ + // ans += Math.floor(num1 / num2); + // num1 %= num2; + // [num1,num2] = [num2,num1]; + // } + // return ans; + + // solution 2. + let ans = 0; + while(num1 !== 0 && num2 !== 0){ + ans += Math.floor(num1 / num2); + num1 %= num2; + // swap nums1 and nums2 + let temp = num1; + num1 = num2; + num2 = temp; + } + return ans; +}; +let num1 = 2, num2 = 3; +// Output: 3 +// Explanation: +// - Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1. +// - Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1. +// - Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1. +// Now num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations. +// So the total number of operations required is 3. +console.log(countOperations(num1,num2)) \ No newline at end of file diff --git a/javascript/LeetCode/Array/2273.js b/javascript/LeetCode/Array/2273.js new file mode 100644 index 0000000..3bd68dc --- /dev/null +++ b/javascript/LeetCode/Array/2273.js @@ -0,0 +1,22 @@ +/** + * 2273. Find Resultant Array After Removing Anagrams + * + * @param {string[]} words + * @return {string[]} + */ +var removeAnagrams = function(words) { + let res = []; + let prevStr = ""; + for(let i = 0;i < words.length;++i) { + let s = words[i].split("").sort().join(""); + + if (s !== prevStr) { + res.push(words[i]); + prevStr = s; + } + } + return res; +}; +let w = ["abba","baba","bbaa","cd","cd"]; +// ["abba","cd"] +console.log(removeAnagrams(w)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/228.js b/javascript/LeetCode/Array/228.js new file mode 100644 index 0000000..6ff10bf --- /dev/null +++ b/javascript/LeetCode/Array/228.js @@ -0,0 +1,28 @@ +/** + * 228. Summary Ranges + * + * 參數為數值陣列,若元素是連續且唯一值,則形成一個range,從第一個連續數值到某一元素,若非連續,則直接push進result array + * + * @param {number[]} nums + * @return {string[]} + */ +var summaryRanges = function(nums) { + let res = []; + let i = 0; + while (i < nums.length) { + let start = i; + while (i + 1 < nums.length && nums[i + 1] === nums[i] + 1) { + i++; + } + if (start === i) { + res.push(nums[start].toString()); + } else { + res.push(nums[start] + "->" + nums[i]); + } + i++; + } + return res; +}; +let nums = [0,1,2,4,5,7]; +// ["0->2","4->5","7"] +console.log(summaryRanges(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/2460.js b/javascript/LeetCode/Array/2460.js new file mode 100644 index 0000000..c710f2a --- /dev/null +++ b/javascript/LeetCode/Array/2460.js @@ -0,0 +1,39 @@ +/** + * 2460. Apply Operations to an Array + * + * 操作n - 1次 + * 若nums[i] === nums[i +1],則將nums[i] * 2,將nums[i+1]改成0 + * 完成所有操作,將所有的0移到陣列最後面 + * 回傳陣列 + * @param {number[]} nums + * @return {number[]} + */ +var applyOperations = function(nums) { + let j = 0; + for(let i = 0;i < nums.length - 1;++i) { + if(nums[i] === nums[i+1]){ + nums[i] *= 2; + nums[i + 1] = 0; + } + } + for(let i = 0;i < nums.length;++i) { + if(nums[i] !== 0){ + nums[j] = nums[i]; + j++; + } + } + while (j < nums.length) { + nums[j++] = 0; + } + return nums; +}; +let nums = [1,2,2,1,1,0] +// Output: [1,4,2,0,0,0] +// Explanation: We do the following operations: +// i = 0: nums[0] and nums[1] are not equal, so we skip this operation. +// i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0]. +// i = 2: nums[2] and nums[3] are not equal, so we skip this operation. +// i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0]. +// i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0]. +// After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0]. +console.log(applyOperations(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/2598.js b/javascript/LeetCode/Array/2598.js new file mode 100644 index 0000000..7f09d66 --- /dev/null +++ b/javascript/LeetCode/Array/2598.js @@ -0,0 +1,30 @@ +/** + * 2598. Smallest Missing Non-negative Integer After Operations + * + * 在一次操作中,可以從任一元素中,加value或減value + * @param {number[]} nums + * @param {number} value + * @return {number} + */ +var findSmallestInteger = function(nums, value) { + const mp = new Array(value).fill(0); + for(let i = 0;i < nums.length;i++) { + const v = ((nums[i] % value) + value) % value; + mp[v]++; + } + // console.log(mp) + let mex = 0; + while(mp[mex % value] > 0){ + mp[mex % value]--; + mex++; + } + return mex; +}; +let nums = [1,-10,7,13,6,8], value = 5; +// Output: 4 +// Explanation: One can achieve this result by applying the following operations: +// - Add value to nums[1] twice to make nums = [1,0,7,13,6,8] +// - Subtract value from nums[2] once to make nums = [1,0,2,13,6,8] +// - Subtract value from nums[3] twice to make nums = [1,0,2,3,6,8] +// The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve. +console.log(findSmallestInteger(nums,value)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/3038.js b/javascript/LeetCode/Array/3038.js new file mode 100644 index 0000000..bb7b817 --- /dev/null +++ b/javascript/LeetCode/Array/3038.js @@ -0,0 +1,24 @@ +/** + * 3038. Maximum Number of Operations With the Same Score I + * + * 以陣列前兩個元素為一組做加總為一步驟,檢查下一組的加總是否跟前一組一樣,若不是,則回傳結果是一樣的步驟有幾個 + * 要能夠取得連續加總值一樣 + * + * @param {number[]} nums + * @return {number} + */ +var maxOperations = function(nums) { + let count = 1; + let firstTwoEleSum = nums[0] + nums[1]; + for(let i = 2;i < nums.length - 1;i+=2) { + if(nums[i] + nums[i+1] === firstTwoEleSum){ + count++; + }else{ + break; + } + } + return count; +}; +let nums = [1,5,3,3,4,1,3,2,2,3]; +// 2 +console.log(maxOperations(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/3289.js b/javascript/LeetCode/Array/3289.js new file mode 100644 index 0000000..64407d8 --- /dev/null +++ b/javascript/LeetCode/Array/3289.js @@ -0,0 +1,38 @@ +/** + * 3289. The Two Sneaky Numbers of Digitville + * + * 參數為數值陣列,回傳元素出現次數大於2的元素。回傳的陣列每個必須是唯一值 + * + * @param {number[]} nums + * @return {number[]} + */ +var getSneakyNumbers = function(nums) { + // element出現次數 >= 2才能被保留 + // 回傳的陣列元素必須是唯一值 + // let map = new Map(); + // let ans = []; + // for(let i = 0;i < nums.length;++i) { + // map.has(nums[i]) ? map.set(nums[i],map.get(nums[i])+ 1) : map.set(nums[i],1); + // } + // for(const [key,value] of map) { + // if(value >= 2){ + // ans.push(key); + // } + // } + // return ans; + + // solution 2. + let set = new Set(); + let result = []; + for(let i = 0;i < nums.length;i++) { + if(set.has(nums[i])){ + result.push(nums[i]); + }else{ + set.add(nums[i]); + } + } + return result; +}; +let nums = [0,1,1,0]; +// [0,1] +console.log(getSneakyNumbers(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/3350.js b/javascript/LeetCode/Array/3350.js new file mode 100644 index 0000000..cc60f1c --- /dev/null +++ b/javascript/LeetCode/Array/3350.js @@ -0,0 +1,32 @@ +/** + * 3350. Adjacent Increasing Subarrays Detection II + * + * 找出連續increase的子陣列,最大長度為? + * 子陣列有2組 + * + * starting at indices a and b (a < b) + * @param {number[]} nums + * @return {number} + */ +var maxIncreasingSubarrays = function(nums) { + let current = 1, previous = 0,ans = 0; + for(let i = 1;i < nums.length;++i) { + if(nums[i - 1] < nums[i]){ + current++; + }else{ + previous = current; + current = 1; + } + ans = Math.max(ans, Math.min(previous, current)); + ans = Math.max(ans, Math.floor(current / 2)); + } + return ans; +}; +let nums = [2,5,7,8,9,2,3,4,3,1]; +/** + * 3 + * The subarray starting at index 2 is [7, 8, 9], which is strictly increasing. + * The subarray starting at index 5 is [2, 3, 4], which is also strictly increasing. + * These two subarrays are adjacent, and 3 is the maximum possible value of k for which two such adjacent strictly increasing subarrays exist. + */ +console.log(maxIncreasingSubarrays(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/3354.js b/javascript/LeetCode/Array/3354.js new file mode 100644 index 0000000..e34d713 --- /dev/null +++ b/javascript/LeetCode/Array/3354.js @@ -0,0 +1,48 @@ +/** + * 3354. Make Array Elements Equal to Zero + * + * curr = index,nums[index] == 0 + * 若curr超過範圍[0,nums.length - 1] 操作結束 + * 若nums[index] == 0,則curr 增加(往右),反之則curr減少(往左) + * nums[index] > 0 ,nums[current] - 1且左右反轉 + * + * @param {number[]} nums + * @return {number} + */ +var countValidSelections = function(nums) { + // you need to find the sum of all the numbers to the left of where nums[i]==0 and the sum of all the numbers to the right of that point. + // If you need more help, look at the detailed explanation in this comment. + let ans = 0; + let sum = nums.reduce((a,b) => a + b,0); + let left = 0,right = sum; + for(let i = 0;i < nums.length;++i) { + if(nums[i] === 0){ + if(left - right >= 0 && left - right <= 1) { + ans++; + } + if(right - left >= 0 && right - left <= 1) { + ans++; + } + }else{ + left += nums[i]; + right -= nums[i]; + } + } + return ans; +}; +let nums = [1,0,2,0,3]; +/** + * 2 + * The only possible valid selections are the following: +Choose curr = 3, and a movement direction to the left. +[1,0,2,0,3] -> [1,0,2,0,3] -> [1,0,1,0,3] -> [1,0,1,0,3] -> [1,0,1,0,2] -> +[1,0,1,0,2] -> [1,0,0,0,2] -> [1,0,0,0,2] -> [1,0,0,0,1] -> [1,0,0,0,1] -> +[1,0,0,0,1] -> [1,0,0,0,1] -> [0,0,0,0,1] -> [0,0,0,0,1] -> [0,0,0,0,1] -> +[0,0,0,0,1] -> [0,0,0,0,0]. + +Choose curr = 3, and a movement direction to the right. +[1,0,2,0,3] -> [1,0,2,0,3] -> [1,0,2,0,2] -> [1,0,2,0,2] -> [1,0,1,0,2] -> +[1,0,1,0,2] -> [1,0,1,0,1] -> [1,0,1,0,1] -> [1,0,0,0,1] -> [1,0,0,0,1] -> +[1,0,0,0,0] -> [1,0,0,0,0] -> [1,0,0,0,0] -> [1,0,0,0,0] -> [0,0,0,0,0]. + */ +console.log(countValidSelections(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/3397.js b/javascript/LeetCode/Array/3397.js new file mode 100644 index 0000000..63c7a1b --- /dev/null +++ b/javascript/LeetCode/Array/3397.js @@ -0,0 +1,28 @@ +/** + * 3397. Maximum Number of Distinct Elements After Operations + * + * 每個元素最多只能加integer(range: -k ~ k)至元素一次 + * 操作完後,回傳陣列元素都是唯一值的有幾個 + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxDistinctElements = function(nums, k) { + // Find the minimum element which is not used for each element. + let ans = 0; + let minValue = -Infinity; + nums.sort((a,b) => a - b); + for(let i = 0;i < nums.length;++i) { + if(minValue > nums[i] + k){ + continue; + } + minValue = Math.max(nums[i] - k,minValue) + 1 + ans++; + } + return ans; +}; +let nums = [1,2,2,3,3,4], k = 2; +// Output: 6 +// Explanation: +// nums changes to [-1, 0, 1, 2, 3, 4] after performing operations on the first four elements. +console.log(maxDistinctElements(nums,k)) \ No newline at end of file diff --git a/javascript/LeetCode/Array/3542.js b/javascript/LeetCode/Array/3542.js new file mode 100644 index 0000000..3d1e269 --- /dev/null +++ b/javascript/LeetCode/Array/3542.js @@ -0,0 +1,38 @@ +/** + * 3542. Minimum Operations to Convert All Elements to Zero + * + * 計算將所有的元素變成0最少需要幾次操作 + * 一次操作中,選子陣列「i,j] (0 <= i <= j < nums.length),並將 + * [start index i,end index j] + * + * @param {number[]} nums + * @return {number} + */ +var minOperations = function(nums) { + let ans = 0; + let arr = []; + for(let i = 0;i < nums.length;++i) { + // 檢查塞入的 element 有沒有 break monoStack 的單線程(遞增or遞減) + while(arr.length && arr[arr.length - 1] > nums[i]){ + // 如果有,把 stack 元素先做調整 + arr.pop(); + } + if(nums[i] === 0){ + continue; + } + if(!arr.length || arr[arr.length - 1] < nums[i]) { + ans++; + arr.push(nums[i]); + } + } + return ans; +}; +let nums = [3,1,2,1]; +/* +3 +Select subarray [1,3] (which is [1,2,1]), where the minimum non-negative integer is 1. Setting all occurrences of 1 to 0 results in [3,0,2,0]. +Select subarray [2,2] (which is [2]), where the minimum non-negative integer is 2. Setting all occurrences of 2 to 0 results in [3,0,0,0]. +Select subarray [0,0] (which is [3]), where the minimum non-negative integer is 3. Setting all occurrences of 3 to 0 results in [0,0,0,0]. +Thus, the minimum number of operations required is 3. +*/ +console.log(minOperations(nums)); diff --git a/javascript/LeetCode/Array/3701.js b/javascript/LeetCode/Array/3701.js new file mode 100644 index 0000000..3d2eedb --- /dev/null +++ b/javascript/LeetCode/Array/3701.js @@ -0,0 +1,28 @@ +/** + * 3701. Compute Alternating Sum + * + * alternating sum :偶數index相加,奇數index相減 + * 偶數[0] - 奇數[1] + 偶數[2] - 奇數[3] + * @param {number[]} nums + * @return {number} + */ +var alternatingSum = function(nums) { + let ans = 0; + for(let i = 0;i < nums.length;i++) { + // 偶數 + if(i % 2 === 0){ + ans += nums[i]; + }else{ + ans -= nums[i] + } + } + return ans; +}; +let nums = [1,3,5,7] +/* +Output: -4 +Elements at even indices are nums[0] = 1 and nums[2] = 5 because 0 and 2 are even numbers. +Elements at odd indices are nums[1] = 3 and nums[3] = 7 because 1 and 3 are odd numbers. +The alternating sum is nums[0] - nums[1] + nums[2] - nums[3] = 1 - 3 + 5 - 7 = -4. +*/ +console.log(alternatingSum(nums)); \ No newline at end of file diff --git a/javascript/LeetCode/Array/3712.js b/javascript/LeetCode/Array/3712.js new file mode 100644 index 0000000..9a846ea --- /dev/null +++ b/javascript/LeetCode/Array/3712.js @@ -0,0 +1,24 @@ +/** + * 3712. Sum of Elements With Frequency Divisible by K + * + * 加總回傳能夠被k整除的element出現次數,在能被k整除的前提下,element出現幾次就是加幾次,例如k = 3,而2出現3次,則2加自己3次(乘自己3次) + * + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var sumDivisibleByK = function(nums, k) { + let ans = 0; + let map = new Map(); + for(let i = 0;i < nums.length;++i) { + map.has(nums[i]) ? map.set(nums[i],map.get(nums[i]) + 1) : map.set(nums[i],1); + } + for(const [key,value] of map) { + if(value % k === 0){ + ans += key * value; + } + } + return ans; +}; +let nums = [1,2,2,3,3,3,3,4], k = 2; +// 16 \ No newline at end of file diff --git a/javascript/LeetCode/Array/3718.js b/javascript/LeetCode/Array/3718.js new file mode 100644 index 0000000..4ba6cca --- /dev/null +++ b/javascript/LeetCode/Array/3718.js @@ -0,0 +1,55 @@ +/** + * 3718. Smallest Missing Multiple of K + * + * 取得能被k整除且是所有能被k整除的最小數且不在nums中的元素並回傳 + * + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var missingMultiple = function(nums, k) { + // solution 1.Runtime 2 ms. + // let divisibleByK = []; + // let ans = 0; + // for(let i = 1;i < nums.length+2;++i) { + // divisibleByK.push(i*k); + // } + // for(let i = 0;i < divisibleByK.length;++i) { + // if(!nums.includes(divisibleByK[i])){ + // ans = divisibleByK[i]; + // break; + // } + // } + // return ans; + + // solution 2.Runtime 1 ms. + // let map = new Map(); + // let ans = 0; + // for(let i = 0;i < nums.length;++i) { + // map.set(nums[i],1); + // } + // for(let i = 1;i < nums.length+2;++i) { + // if(!map.has(i * k)){ + // ans = i * k; + // break; + // } + // } + // return ans; + + // solution 3. + let set = new Set(nums); + for(let i = k;;i+=k) { + if(!set.has(i)){ + return i; + } + } +}; +// let nums = [1,4,7,10,15], k = 5; +// 5 +let nums = [8,2,3,4,6], k = 2; +// 10 +// let nums = [99],k = 99; +// 198 +// let nums = [2,4,6,8,10],k = 2; +// 12 +console.log(missingMultiple(nums,k)); \ No newline at end of file diff --git a/javascript/LeetCode/String/1021.js b/javascript/LeetCode/String/1021.js new file mode 100644 index 0000000..1319e0f --- /dev/null +++ b/javascript/LeetCode/String/1021.js @@ -0,0 +1,32 @@ +/** + * 1021. Remove Outermost Parentheses + * + * @param {string} s + * @return {string} + */ +var removeOuterParentheses = function(s) { + // () 須相等數量,才能變成一對 + let splitS = s.split(""); + let res = ""; + let count = 1; + for(let i = 1; i < splitS.length;++i) { + if(splitS[i] === "("){ + count++; + if(count > 1){ + res += "("; + } + }else{ + if(count > 1){ + res += ")"; + } + count--; + } + } + return res; +}; +// let s = "(()())(())" +// "()()()" +let s = "(()())(())(()(()))"; +// "()()()()(())" +// "(()()) (())(()(()))" => (()()) +console.log(removeOuterParentheses(s)); \ No newline at end of file diff --git a/javascript/LeetCode/String/1844.js b/javascript/LeetCode/String/1844.js new file mode 100644 index 0000000..82c7978 --- /dev/null +++ b/javascript/LeetCode/String/1844.js @@ -0,0 +1,33 @@ +/** + * 1844. Replace All Digits with Characters + * + * @param {string} s + * @return {string} + */ +var replaceDigits = function(s) { + const reg = new RegExp('^[0-9]+$'); + // 數字前面的一個字母表示該字母要往後增加幾個才能變成新字母。a2 => a後面的第2個字母,回傳ac + // 數字所在index都是奇數 + let res = ""; + for(let i = 0;i < s.length;++i) { + // 前一個(字母) + let prev = s[i - 1]; + // 目前所在位置(數字) + let next = s[i]; + if(i % 2 !== 0){ + // char.charCodeAt() 取得ascii + // ascii 轉字母 String.fromCharCode(ascii) + res += String.fromCharCode(prev.charCodeAt() + parseInt(next)) + }else{ + res += s[i]; + } + } + return res; +}; +let s = "a1c1e1" +// Output: "abcdef" +// Explanation: The digits are replaced as follows: +// - s[1] -> shift('a',1) = 'b' +// - s[3] -> shift('c',1) = 'd' +// - s[5] -> shift('e',1) = 'f' +console.log(replaceDigits(s)); \ No newline at end of file diff --git a/javascript/LeetCode/String/1935.js b/javascript/LeetCode/String/1935.js new file mode 100644 index 0000000..4878637 --- /dev/null +++ b/javascript/LeetCode/String/1935.js @@ -0,0 +1,24 @@ +/** + * 1935. Maximum Number of Words You Can Type + * + * @param {string} text + * @param {string} brokenLetters + * @return {number} + */ +var canBeTypedWords = function(text, brokenLetters) { + const broken = new Set(brokenLetters); + const split = text.split(" "); + let ans = 0; + + for(const t of split) { + for(const c of t) { + if(broken.has(c)){ + ans++; + } + } + } + return ans; +}; +let text = "hello world", brokenLetters = "ad"; +// 1 +console.log(canBeTypedWords(text,brokenLetters)); \ No newline at end of file diff --git a/javascript/LeetCode/String/2315.js b/javascript/LeetCode/String/2315.js new file mode 100644 index 0000000..d35c86f --- /dev/null +++ b/javascript/LeetCode/String/2315.js @@ -0,0 +1,50 @@ +/** + * 2315. Count Asterisks + * + * 給一個字串,字串中可能會有"|"和"*",找出字串中被一組 | 包住的連續 ** 有幾個 + * @param {string} s + * @return {number} + */ +var countAsterisks = function(s) { + // 須判斷字串中是否有連續的"*"符號 + // 拆成陣列,計算一組"|"中有幾個連續"*" + + // solution 1. + // let splitS = s.split(""); + // let ans = 0; + // let pairs = false; + // for(let i = 0;i < splitS.length;++i) { + // if(splitS[i] === "|"){ + // if(pairs){ + // pairs = false; + // continue; + // }else{ + // pairs = true; + // continue; + // } + // } + // if(pairs === false && splitS[i] === "*"){ + // ans++; + // } + // } + // return ans; + + + // solution 2. + let ans = 0, bars = 0; + for(let i = 0;i < s.length;++i) { + // bars必須要一對(偶數) + if(s[i] === "*" && bars % 2 === 0){ + ans++; + } + if(s[i] === "|"){ + bars++; + } + } + return ans; +}; +// let s = "l|*e*et|c**o|*de|" +// Output: 2 +let s = "yo|uar|e**|b|e***au|tifu|l"; +// 5 +console.log(countAsterisks(s)) \ No newline at end of file diff --git a/javascript/LeetCode/String/242.js b/javascript/LeetCode/String/242.js new file mode 100644 index 0000000..898eef9 --- /dev/null +++ b/javascript/LeetCode/String/242.js @@ -0,0 +1,34 @@ +/** + * 242. Valid Anagram + * + * 在兩個字串參數字母重新排列的情況下,是否可以構成Anagram + * + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = function(s, t) { + // solutipon 1. + // let splitS = s.split("").sort(); + // let splitT = t.split("").sort(); + // return splitS.join("") === splitT.join(""); + + // hash map + if (s.length !== t.length) { + return false; + } + let map = new Map(); + for(let i = 0;i < s.length;i++) { + map.set(s[i], (map.get(s[i]) || 0) + 1); + } + for(let i = 0;i < t.length;i++) { + if(!map.has(t[i]) || map.get(t[i]) === 0){ + return false; + } + map.set(t[i], map.get(t[i]) - 1); + } + return true; +}; +let s = "aacc", t = "ccac" +// false +console.log(isAnagram(s,t)); \ No newline at end of file diff --git a/javascript/LeetCode/String/3461.js b/javascript/LeetCode/String/3461.js new file mode 100644 index 0000000..a69c792 --- /dev/null +++ b/javascript/LeetCode/String/3461.js @@ -0,0 +1,38 @@ +/** + * 3461. Check If Digits Are Equal in String After Operations I + * + * 重複步驟直到參數字串只剩2位數 + * + * 從左邊開始的第一位數跟第二位數相加再 % 10 = 新的左邊第一位數,第二位數跟後面一位數相加再 %10 = 新的左邊第二位數,以此類推形成新的s + * 將新的s再跟上面的步驟一樣直到剩下2位數,並比較這兩位數是否一樣 + * @param {string} s + * @return {boolean} + */ +var hasSameDigits = function(s) { + while(s.length > 2){ + let newS = ""; + for(let i = 0;i < s.length - 1;++i) { + let sum = (parseInt(s[i]) + parseInt(s[i + 1])) % 10; + newS += sum.toString(); + } + s = newS; + } + return s[0] === s[1]; +}; +let s = "3902"; +/** + * true + * Initially, s = "3902" + * First operation: + * (s[0] + s[1]) % 10 = (3 + 9) % 10 = 2 + * (s[1] + s[2]) % 10 = (9 + 0) % 10 = 9 + * (s[2] + s[3]) % 10 = (0 + 2) % 10 = 2 + * s becomes "292" + * + * Second operation: + * (s[0] + s[1]) % 10 = (2 + 9) % 10 = 1 + * (s[1] + s[2]) % 10 = (9 + 2) % 10 = 1 + * s becomes "11" + * Since the digits in "11" are the same, the output is true. + */ +console.log(hasSameDigits(s)); \ No newline at end of file diff --git a/javascript/LeetCode/math/1716.js b/javascript/LeetCode/math/1716.js new file mode 100644 index 0000000..2e9ab2a --- /dev/null +++ b/javascript/LeetCode/math/1716.js @@ -0,0 +1,30 @@ +/** + * 1716. Calculate Money in Leetcode Bank + * + * 給一個數字N,表示會存N天的錢,存錢的起始值為1(星期一),每隔一天增加1元,直到第7天(星期天)為止 + * 而下一禮拜存錢起始值會比上禮拜一多1元,回傳這N天總共存了多少錢 + * @param {number} n + * @return {number} + */ +var totalMoney = function(n) { + // 禮拜一(第一天)存1元,之後的每一天,會存比前一天還多一元的錢 + // 一個禮拜有7天,每個禮拜一會存得比上禮拜一存的錢多一元 + let sum = 0; + let start = 1; + while(n > 0){ + for(let i = start;i < start + 7 && n > 0;++i) { + sum += i; + n--; + } + start++; + } + return sum; +}; +// let n = 10; +// 37 +// After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. +// let n = 4; +// 10 +let n = 20; +// 96 +console.log(totalMoney(n)); \ No newline at end of file diff --git a/javascript/LeetCode/math/1925.js b/javascript/LeetCode/math/1925.js new file mode 100644 index 0000000..9d30967 --- /dev/null +++ b/javascript/LeetCode/math/1925.js @@ -0,0 +1,44 @@ +/** + * 1925. Count Square Sum Triples + * + * triple = a 二次方 + b 二次方 = c 二次方 + * + * Hints: + * 1.Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n + * 2.You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt + * + * @param {number} n + * @return {number} + */ +var countTriples = function(n) { + // solution 1. + // let ans = 0; + // for(let i = 1;i <= n;++i) { + // for(let j = 1;j <= n;++j) { + // for(let k = 1;k <= n;++k) { + // if((i ** 2) + (j ** 2) === (k ** 2)){ + // ans++; + // } + // } + // } + // } + // return ans; + + + // solution 2. + let ans = 0; + for(let i = 1;i <= n;++i) { + for(let j = i + 1;j <= n;++j) { + // a & b + let pairs = Math.sqrt((i ** 2) + (j ** 2)); + if(Number.isInteger(pairs) && pairs <= n) { + ans += 2; + } + } + } + return ans; +}; +let n = 5; +// 2 +// The square triples are (3,4,5) and (4,3,5). +console.log(countTriples(n)); \ No newline at end of file diff --git a/javascript/LeetCode/math/2654.js b/javascript/LeetCode/math/2654.js new file mode 100644 index 0000000..c1215d0 --- /dev/null +++ b/javascript/LeetCode/math/2654.js @@ -0,0 +1,59 @@ +/** + * 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 + * + * GCD = 最大公因數」(Greatest Common Divisor) + * 陣列元素可操作數次,選任一index i (0 <= i < nums.length - 1)並取得nums[i] or nums[i + 1]的GCD + * 若可讓每個元素都=1的話,回傳1,否則-1 + * + * @param {number[]} nums + * @return {number} + */ +var minOperations = function(nums) { + let g = 0,nums1 = 0; + + function mygcd(x,y){ + // 求x & y 的最大公約數 + // x & y 可能是很大的數 + if (y === 0) { + return x; + } + return mygcd(y, x % y); + } + + for(const a of nums) { + if(a === 1) { + nums1++; + } + g = mygcd(g,a); + } + if(nums1 > 0) { + return nums.length - nums1; + } + if(g > 1) { + return -1; + } + + let minLen = nums.length; + for (let i = 0; i < nums.length; ++i) { + let currentGcd = 0; + for (let j = i; j < nums.length; ++j) { + currentGcd = mygcd(currentGcd, nums[j]); + if(currentGcd === 1) { + minLen = Math.min(minLen, j - i + 1); + break; + } + } + } + return minLen + nums.length - 2; + +}; +// let nums = [2,6,3,4]; +// 4 +// Explanation: We can do the following operations: +// - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. +// - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. +// - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. +// - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. +let nums = [1,1]; +// 0 +console.log(minOperations(nums)); \ No newline at end of file diff --git a/javascript/codewar/array/16.js b/javascript/codewar/array/16.js new file mode 100644 index 0000000..bf7a4c4 --- /dev/null +++ b/javascript/codewar/array/16.js @@ -0,0 +1,23 @@ +/** + * Parts of a list (7 kyu) + * + * Divide a list (an array) of at least two elements into two non-empty parts. + * Elements of a pair must be in the same order as in the original array. + * + * @param {string} arr + * @return {string} 二維陣列 + */ +function partlist(arr) { + let result = []; + for(let i = 1;i < arr.length;++i) { + let inside = []; + inside.push(arr.slice(0,i).join(" ")); + inside.push(arr.slice(i).join(" ")); + result.push(inside); + } + return result; +} +let arr = ["I", "wish", "I", "hadn't", "come"]; +// let expect = [["I", "wish I hadn't come"], ["I wish", "I hadn't come"], ["I wish I", "hadn't come"], ["I wish I hadn't", "come"]] +// console.log(assert.deepEqual(partlist(arr),expect)); +console.log(partlist(arr)); \ No newline at end of file diff --git a/javascript/index.js b/javascript/index.js index f00c3fa..2d5a115 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1045,4 +1045,44 @@ var fractionToDecimal = function(numerator, denominator) { }; let numerator = 1, denominator = 2; // "0.5" -// console.log(fractionToDecimal(numerator,denominator)); \ No newline at end of file +// console.log(fractionToDecimal(numerator,denominator)); + + + +/** + * 3318. Find X-Sum of All K-Long Subarrays I + * + * 計算每個元素出現次數但只保留出現次數 = x 次的元素,若有超過2個元素,則只保留元素較大的那個 + * 以陣列型態計算連續子陣列元素總和 + * + * @param {number[]} nums + * @param {number} k + * @param {number} x + * @return {number[]} + */ +var findXSum = function(nums, k, x) { + // 將nums切成長度 = k的陣列,並計算在該陣列裡面有幾個元素出現次數 = x的 + // 最後將符合的加總,並組成新陣列,形成元素i + let res = []; + // let map = new Map(); + // for(let i = 0;i < k;++i) { + // map.has(nums[i]) ? map.set(nums[i],map.get(nums[i]) + 1) : map.set(nums[i],1); + // } + let i = 0; + while(i < k){ + let sub = nums[i]; + console.log(sub); + i++; + } + // for(let i = 0;i < k;++i) { + // console.log(nums[i]) + // } + +}; +// let nums = [1,1,2,2,3,4,2,3], k = 6, x = 2; +// [6,10,12] +// For subarray [1, 1, 2, 2, 3, 4], only elements 1 and 2 will be kept in the resulting array. Hence, answer[0] = 1 + 1 + 2 + 2. +// For subarray [1, 2, 2, 3, 4, 2], only elements 2 and 4 will be kept in the resulting array. Hence, answer[1] = 2 + 2 + 2 + 4. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times. +// For subarray [2, 2, 3, 4, 2, 3], only elements 2 and 3 are kept in the resulting array. Hence, answer[2] = 2 + 2 + 2 + 3 + 3. +// console.log(findXSum(nums,k,x)); + diff --git a/python/index.py b/python/index.py index 2b0efb1..f532269 100644 --- a/python/index.py +++ b/python/index.py @@ -9,6 +9,7 @@ """ from math import sqrt from typing import List +from collections import Counter # from numpy import diff # module @@ -25,14 +26,14 @@ from oop.Lion import Lion from oop.Behavior import move -greek = Tortoise("福氣",7,"veggie","地中海型陸龜") -greek.eat() -greek.hibernation() -greek.environment() -greek.attack() -greek.affend() -print(greek.specice) -print(greek.avgWeight(7,5)) +# greek = Tortoise("福氣",7,"veggie","地中海型陸龜") +# greek.eat() +# greek.hibernation() +# greek.environment() +# greek.attack() +# greek.affend() +# print(greek.specice) +# print(greek.avgWeight(7,5)) # lion = Lion("獅子","未知","肉食") # lion.eat() @@ -250,3 +251,18 @@ def isPrime(element:int): # print(closestPrimes(left,right)) +def replaceDigits(s: str) -> str: + res = "" + for i in range(len(s)): + prev = s[i - 1] + current = s[i] + + if i % 2 != 0: + res += chr(ord(prev) + int(current)) + else: + res += s[i] + + return res +s = "a1c1e1" +# Output: "abcdef" +# print(replaceDigits(s)) \ No newline at end of file diff --git a/python/leetcode/list/2273.py b/python/leetcode/list/2273.py new file mode 100644 index 0000000..a2f8084 --- /dev/null +++ b/python/leetcode/list/2273.py @@ -0,0 +1,23 @@ +from typing import List +def removeAnagrams(words: List[str]) -> List[str]: + ''' + 2273. Find Resultant Array After Removing Anagrams + 在一次操作中,選擇任何一個索引值 i 使得 0 < i < words.length 且 words[i - 1] 與 words[i] 互相為易位構詞(Anagram), + 並將 words[i] 從 words 中刪除。只要你可以選擇滿足這些條件的索引值,持續執行此操作。 + 回傳執行所有操作後的 words。可以證明在每一次操作以任意順序選擇這些索引值將得到相同的結果。 + + + 直接掃過一次 words,只要遇到 words[i] 與 words[i - 1] 是易位構詞就把 words[i] 刪掉即可。 + ''' + res = [] + s = "" + for i in range(0,len(words)): + split = "".join(sorted(words[i])) + if s != split: + res.append(words[i]) + s = split + + return res +w = ["abba","baba","bbaa","cd","cd"] +# ["abba","cd"] +print(removeAnagrams(w)) \ No newline at end of file diff --git a/python/leetcode/list/3038.py b/python/leetcode/list/3038.py new file mode 100644 index 0000000..12af81f --- /dev/null +++ b/python/leetcode/list/3038.py @@ -0,0 +1,16 @@ +from typing import List +def maxOperations(nums: List[int]) -> int: + ''' + 3038. Maximum Number of Operations With the Same Score I + ''' + count = 1 + firstTwoEleSum = nums[0] + nums[1] + for i in range(2,len(nums) - 1,2): + if nums[i] + nums[i+1] == firstTwoEleSum: + count+=1 + else: + break + return count + +nums = [3,2,1,4,5] +print(maxOperations(nums)) \ No newline at end of file diff --git a/python/leetcode/list/3289.py b/python/leetcode/list/3289.py new file mode 100644 index 0000000..2f07b16 --- /dev/null +++ b/python/leetcode/list/3289.py @@ -0,0 +1,24 @@ +from collections import Counter +from typing import List +def getSneakyNumbers(nums: List[int]) -> List[int]: + ''' + 3289. The Two Sneaky Numbers of Digitville + + 參數為數值陣列,回傳元素出現次數大於2的元素。 + 回傳的陣列每個必須是唯一值 + ''' + # use counter,可計算出現次數 + # c = Counter(nums) + # ans = [] + # for key, value in c.items(): + # if value == 2: + # ans.append(key) + # return ans + + # solution 2.更簡潔寫法 + c = Counter(nums) + return [key for key,value in c.items() if value == 2] + +nums = [7,1,5,4,3,4,6,0,9,5,8,2] +# [4,5] +print(getSneakyNumbers(nums)) \ No newline at end of file diff --git a/python/leetcode/list/3467.py b/python/leetcode/list/3467.py new file mode 100644 index 0000000..2de1460 --- /dev/null +++ b/python/leetcode/list/3467.py @@ -0,0 +1,40 @@ +from typing import List + +def transformArray(nums: List[int]) -> List[int]: + ''' + 3467. Transform Array by Parity + + 將nums的element是偶數的替換成0 + 將nums的的element是奇數位替換成1 + 遞增排序結果 + ''' + # solution 1 + # res = [] + # for i in range(len(nums)): + # if nums[i] % 2 == 0: + # res.append(0) + # else: + # res.append(1) + # res.sort() + # return res + + + # solution 2. + # 2 pointers + res = [0] * len(nums) + left = 0 + right = len(nums) - 1 + + for i in nums: + if i % 2 == 0: + res[left] = 0 + left+=1 + else: + res[right] = 1 + right-=1 + return res + + +nums = [1,5,1,4,2] +# [0,0,1,1,1] +print(transformArray(nums)) \ No newline at end of file diff --git a/python/leetcode/list/3668.py b/python/leetcode/list/3668.py new file mode 100644 index 0000000..918fb5c --- /dev/null +++ b/python/leetcode/list/3668.py @@ -0,0 +1,22 @@ +from typing import List + +def recoverOrder(order: List[int], friends: List[int]) -> List[int]: + ''' + 3668. Restore Finishing Order + + 兩個數值陣列參數分別是order、friends + order內的元素表示friends的id完賽順序,friends則是他們各自的id,依照order順序,回傳friends完賽的有誰。 + ''' + ans = [] + for i in range(len(order)): + if order[i] in friends: + ans.append(order[i]) + return ans + + # solition 2. + # ans = set(friends) + # return [i for i in order if i in ans] +order = [3,1,2,5,4] +friends = [1,3,4] +# [3,1,4] +print(recoverOrder(order,friends)) \ No newline at end of file diff --git a/python/leetcode/list/3712 .py b/python/leetcode/list/3712 .py new file mode 100644 index 0000000..75f2ee2 --- /dev/null +++ b/python/leetcode/list/3712 .py @@ -0,0 +1,18 @@ +from typing import List +def sumDivisibleByK(nums: List[int], k: int) -> int: + ''' + 3712. Sum of Elements With Frequency Divisible by K + ''' + ans = 0 + counts = {} + for i in nums: + counts[i] = counts.get(i, 0) + 1 + + for key,value in counts.items(): + if value % k == 0: + ans += key * value + return ans + +nums = [1,2,2,3,3,3,3,4] +k = 2 +print(sumDivisibleByK(nums,k)) \ No newline at end of file diff --git a/python/oop/Tortoise.py b/python/oop/Tortoise.py index da5b947..b7d6893 100644 --- a/python/oop/Tortoise.py +++ b/python/oop/Tortoise.py @@ -12,6 +12,10 @@ def __init__(self, name, age, food,speciceType:str): super().__init__(name, age, food) self.speciceType = speciceType + def eat(self): + cant = ["草酸高食物","糖份高,例如水果","人類的食物"] + + print(f"{self.food},但有些不適合吃") def environment(self): ''' diff --git a/python/oop/__pycache__/Tortoise.cpython-312.pyc b/python/oop/__pycache__/Tortoise.cpython-312.pyc index 11e71fa..bfca32a 100644 Binary files a/python/oop/__pycache__/Tortoise.cpython-312.pyc and b/python/oop/__pycache__/Tortoise.cpython-312.pyc differ