From 7712c070a52c50d1b9c5d28dc38c5efe546a449e Mon Sep 17 00:00:00 2001 From: Mavis Date: Thu, 2 Oct 2025 14:18:15 +0800 Subject: [PATCH 01/27] add solutions --- javascript/LeetCode/Array/1534.js | 32 +++++++++++++++++++++++++++++++ javascript/LeetCode/Array/1913.js | 17 +++++++++++++--- 2 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 javascript/LeetCode/Array/1534.js 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 From 50fb9424536d2f1607790eac9148d0bd3d97594d Mon Sep 17 00:00:00 2001 From: Mavis Date: Fri, 3 Oct 2025 14:38:32 +0800 Subject: [PATCH 02/27] add 1935 --- javascript/LeetCode/String/1935.js | 24 ++++++++++++++++++++++++ javascript/index.js | 3 ++- 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 javascript/LeetCode/String/1935.js 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/index.js b/javascript/index.js index f00c3fa..f5e9b99 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1045,4 +1045,5 @@ 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)); + From 0f38cb4c5fd02ab8520f7cca26699c3e12a0cd57 Mon Sep 17 00:00:00 2001 From: Mavis Date: Tue, 7 Oct 2025 14:17:43 +0800 Subject: [PATCH 03/27] add 3701 --- javascript/LeetCode/Array/3701.js | 28 +++++++++++++++++++++++++++ javascript/index.js | 32 +++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 javascript/LeetCode/Array/3701.js 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/index.js b/javascript/index.js index f5e9b99..2eccefc 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1047,3 +1047,35 @@ let numerator = 1, denominator = 2; // "0.5" // console.log(fractionToDecimal(numerator,denominator)); +/** + * 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 From dab6cb30d5e921e74a7c747bb2b8307f0049bdd3 Mon Sep 17 00:00:00 2001 From: Mavis Date: Wed, 8 Oct 2025 15:02:22 +0800 Subject: [PATCH 04/27] solve 2 problems and no.2315 unsolve. --- javascript/LeetCode/String/1021.js | 32 +++++++++++++++++++++ javascript/LeetCode/String/1844.js | 33 ++++++++++++++++++++++ javascript/index.js | 45 +++++++++++++++--------------- python/index.py | 41 ++++++++++++++++++--------- 4 files changed, 115 insertions(+), 36 deletions(-) create mode 100644 javascript/LeetCode/String/1021.js create mode 100644 javascript/LeetCode/String/1844.js 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/index.js b/javascript/index.js index 2eccefc..3eceb1d 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1048,34 +1048,33 @@ let numerator = 1, denominator = 2; // console.log(fractionToDecimal(numerator,denominator)); /** - * 1021. Remove Outermost Parentheses + * 2315. Count Asterisks * + * 給一個字串,字串中可能會有"|"和"*",找出字串中被一組 | 包住的連續 ** 有幾個 * @param {string} s - * @return {string} + * @return {number} */ -var removeOuterParentheses = function(s) { - // () 須相等數量,才能變成一對 +var countAsterisks = 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 += ")"; + let ans = 0; + let pairs = false; + for(let i = 0;i < splitS.length;++i) { + if(splitS[i] === "|"){ + if(pairs){ + pairs = true; + continue; + }else{ + pairs = false; } - count--; } + } - return res; + return ans; }; -// let s = "(()())(())" -// "()()()" -let s = "(()())(())(()(()))"; -// "()()()()(())" -// "(()()) (())(()(()))" => (()()) -console.log(removeOuterParentheses(s)); \ No newline at end of file +// 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/python/index.py b/python/index.py index 2b0efb1..b3b9f37 100644 --- a/python/index.py +++ b/python/index.py @@ -20,19 +20,19 @@ # oop # from file name(module) import the class. -from oop.Animal import Animal -from oop.Tortoise import Tortoise -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)) +# from oop.Animal import Animal +# from oop.Tortoise import Tortoise +# 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)) # lion = Lion("獅子","未知","肉食") # lion.eat() @@ -250,3 +250,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 From fc1ff4fa16e1fa6fbe6bee82e25369775d5f6539 Mon Sep 17 00:00:00 2001 From: Mavis Date: Thu, 9 Oct 2025 13:57:04 +0800 Subject: [PATCH 05/27] add 2315 --- javascript/LeetCode/String/2315.js | 50 ++++++++++++++++++++++++++++++ javascript/index.js | 31 ------------------ 2 files changed, 50 insertions(+), 31 deletions(-) create mode 100644 javascript/LeetCode/String/2315.js 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/index.js b/javascript/index.js index 3eceb1d..f5e9b99 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1047,34 +1047,3 @@ let numerator = 1, denominator = 2; // "0.5" // console.log(fractionToDecimal(numerator,denominator)); -/** - * 2315. Count Asterisks - * - * 給一個字串,字串中可能會有"|"和"*",找出字串中被一組 | 包住的連續 ** 有幾個 - * @param {string} s - * @return {number} - */ -var countAsterisks = function(s) { - // 須判斷字串中是否有"*"符號 - // 拆成陣列,計算一組"|"中有幾個連續"*" - let splitS = s.split(""); - let ans = 0; - let pairs = false; - for(let i = 0;i < splitS.length;++i) { - if(splitS[i] === "|"){ - if(pairs){ - pairs = true; - continue; - }else{ - pairs = false; - } - } - - } - 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 From 93abed1f194650050dca8572c620a7b8eb8b1bfe Mon Sep 17 00:00:00 2001 From: Mavis Date: Mon, 13 Oct 2025 14:55:57 +0800 Subject: [PATCH 06/27] add 2273 --- javascript/LeetCode/Array/2273.js | 22 ++++++++++++++++++++++ python/index.py | 3 ++- python/leetcode/list/2273.py | 23 +++++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 javascript/LeetCode/Array/2273.js create mode 100644 python/leetcode/list/2273.py 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/python/index.py b/python/index.py index b3b9f37..9b05c55 100644 --- a/python/index.py +++ b/python/index.py @@ -264,4 +264,5 @@ def replaceDigits(s: str) -> str: return res s = "a1c1e1" # Output: "abcdef" -print(replaceDigits(s)) \ No newline at end of file +print(replaceDigits(s)) + 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 From 4d5e1463fbc7918d9d28ca6335902acf7529c2ff Mon Sep 17 00:00:00 2001 From: Mavis Date: Tue, 14 Oct 2025 14:34:38 +0800 Subject: [PATCH 07/27] add 242 --- javascript/LeetCode/String/242.js | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 javascript/LeetCode/String/242.js 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 From 77219092d7b28a8487f672765af5469fb9ce6477 Mon Sep 17 00:00:00 2001 From: Mavis Date: Wed, 15 Oct 2025 14:55:08 +0800 Subject: [PATCH 08/27] add 2 problems --- javascript/LeetCode/Array/3350.js | 32 ++++++++++++++++++++++ javascript/LeetCode/math/1925.js | 44 +++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 javascript/LeetCode/Array/3350.js create mode 100644 javascript/LeetCode/math/1925.js 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/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 From b46553e7663b2d58d8397b87dc269e3fdc22f379 Mon Sep 17 00:00:00 2001 From: Mavis Date: Thu, 16 Oct 2025 14:52:23 +0800 Subject: [PATCH 09/27] add 3712 --- javascript/LeetCode/Array/3712.js | 24 ++++++++++++++++++++++++ javascript/index.js | 2 ++ python/index.py | 3 ++- python/leetcode/list/3712 .py | 18 ++++++++++++++++++ 4 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 javascript/LeetCode/Array/3712.js create mode 100644 python/leetcode/list/3712 .py 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/index.js b/javascript/index.js index f5e9b99..df33458 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1047,3 +1047,5 @@ let numerator = 1, denominator = 2; // "0.5" // console.log(fractionToDecimal(numerator,denominator)); + +console.log(sumDivisibleByK(nums,k)); \ No newline at end of file diff --git a/python/index.py b/python/index.py index 9b05c55..a1d209b 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 @@ -264,5 +265,5 @@ def replaceDigits(s: str) -> str: return res s = "a1c1e1" # Output: "abcdef" -print(replaceDigits(s)) +# print(replaceDigits(s)) 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 From 1df6bd13554ffd8597432a804e86db07133a3f7e Mon Sep 17 00:00:00 2001 From: Mavis Date: Fri, 17 Oct 2025 14:24:43 +0800 Subject: [PATCH 10/27] add 2598 --- javascript/LeetCode/Array/228.js | 28 ++++++++++++++++++++++++++++ javascript/LeetCode/Array/2598.js | 30 ++++++++++++++++++++++++++++++ javascript/index.js | 2 -- 3 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 javascript/LeetCode/Array/228.js create mode 100644 javascript/LeetCode/Array/2598.js 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/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/index.js b/javascript/index.js index df33458..f5e9b99 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1047,5 +1047,3 @@ let numerator = 1, denominator = 2; // "0.5" // console.log(fractionToDecimal(numerator,denominator)); - -console.log(sumDivisibleByK(nums,k)); \ No newline at end of file From a8ba9dff03382bf96f64a8a4a71c60f2df1c9e97 Mon Sep 17 00:00:00 2001 From: Mavis Date: Sat, 18 Oct 2025 10:23:00 +0800 Subject: [PATCH 11/27] add a solution --- javascript/LeetCode/Array/3397.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 javascript/LeetCode/Array/3397.js 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 From d03288b5e48babedb2104d7863927fe23e6bb086 Mon Sep 17 00:00:00 2001 From: Mavis Date: Tue, 21 Oct 2025 15:03:27 +0800 Subject: [PATCH 12/27] add 3038 fot JS and Python --- javascript/LeetCode/Array/3038.js | 24 ++++++++++++++++++ python/index.py | 12 ++++----- python/leetcode/list/3038.py | 16 ++++++++++++ python/oop/Tortoise.py | 4 +++ .../oop/__pycache__/Tortoise.cpython-312.pyc | Bin 2134 -> 2343 bytes 5 files changed, 50 insertions(+), 6 deletions(-) create mode 100644 javascript/LeetCode/Array/3038.js create mode 100644 python/leetcode/list/3038.py 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/python/index.py b/python/index.py index a1d209b..c4ecf17 100644 --- a/python/index.py +++ b/python/index.py @@ -21,13 +21,13 @@ # oop # from file name(module) import the class. -# from oop.Animal import Animal -# from oop.Tortoise import Tortoise -# from oop.Lion import Lion -# from oop.Behavior import move +from oop.Animal import Animal +from oop.Tortoise import Tortoise +from oop.Lion import Lion +from oop.Behavior import move -# greek = Tortoise("福氣",7,"veggie","地中海型陸龜") -# greek.eat() +greek = Tortoise("福氣",7,"veggie","地中海型陸龜") +greek.eat() # greek.hibernation() # greek.environment() # greek.attack() 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/oop/Tortoise.py b/python/oop/Tortoise.py index da5b947..680a088 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 11e71fa8ecdc6c978663e3fd904492ae951ce839..ce1b9868d3b816f16d191bd620d91bd9b7cb5c5c 100644 GIT binary patch delta 426 zcmca6uw01mG%qg~0}yO_{4Ilxbs}FTW5C1;eYF&}7KSK}4u&+w6!sR5D9#iPAfGFR z6G(D*FjO!`@dPtya&0^w#VE-F)XfaUpG|tE0q8$c)zFT$=H&HDAQfUjqJiNK2k!)t>5>yACvaboHom~l zXL6Opv`BEXAk#HQ)*@k`n#u2&Ll}iNJG1aHGAd6FV(ny9nS6&;l2Lu~H`Y=%kcuLa z$;E8yjM|fDvn8^rK?IoC)ur@+%wkYzfvxGtyUHP3Bnaec@=kVUw~!JAsgwl~N+3c7 zM5u!Z&B+tkjTJ$`^P`2~0|x`YVuSk!7G_rU4aQ#?fYc{0Mpm;=Y?JS^2QnH>HslcF Q*JhOKDErC)q`(#c0N8M8v;Y7A delta 245 zcmZ23bWMQoG%qg~0}!mVx|Xq*Wg=fDqu0a=eT5E&G{zLR7LF*66!sQ|D9#iPAj#Fi zP{A0*9n7G~x$$fidDv^-< zqLTc~;#9qi%%s$!yu^~s{5;jk``Jo4L_xMP7I9CuVpnI>oSej-$fgVwDpHwz5-6ZE z`6IgoBhO?m4hvB!kgz<60GU~&3L?}e$8Z=k>QA1)Aq7;mfg@1O04U4|#Kj^&;sY}y YBjZyB*)J@bjB*`iUm1W@kswe405e=Wc>n+a From 9f33342f244620367000004e597e0c216ca3d56c Mon Sep 17 00:00:00 2001 From: Mavis Date: Wed, 22 Oct 2025 14:15:35 +0800 Subject: [PATCH 13/27] add JS one problem solution --- javascript/LeetCode/Array/2460.js | 39 ++++++++++++++++++ python/oop/Tortoise.py | 2 +- .../oop/__pycache__/Tortoise.cpython-312.pyc | Bin 2343 -> 2420 bytes 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 javascript/LeetCode/Array/2460.js 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/python/oop/Tortoise.py b/python/oop/Tortoise.py index 680a088..b7d6893 100644 --- a/python/oop/Tortoise.py +++ b/python/oop/Tortoise.py @@ -13,7 +13,7 @@ def __init__(self, name, age, food,speciceType:str): self.speciceType = speciceType def eat(self): - cant = ["草酸高食物","糖份高,例如水果"] + cant = ["草酸高食物","糖份高,例如水果","人類的食物"] print(f"{self.food},但有些不適合吃") diff --git a/python/oop/__pycache__/Tortoise.cpython-312.pyc b/python/oop/__pycache__/Tortoise.cpython-312.pyc index ce1b9868d3b816f16d191bd620d91bd9b7cb5c5c..de922b05296bc2be3300d6206f32caafb4d10575 100644 GIT binary patch delta 292 zcmZ23^hJpGG%qg~0}zP+`j+9lkyn|C&j!ew&XB^G!j#Tb%Q)GLN!gisF4Jm8kSYcS zMutiTO%}gWejxirZ|BR_9WPhUc)57~^Ujr}5alKjl#R6QUMWI?ea zkZ54IA)t6c$>svTZ3oMf&BvKsm>5Mi^RV(UGOA9NW?RgtIe9-@CCf_2BJRmn?COlV zlatuf7}Y1A1hNe#e`HT((*T-Mq%}E)!=IIz)$9}3>`s_GO0~&W*3%Y zPE9PS;t9zwD#_0*PSpeQ_<@Rx#ehTu!=24S%q~ofLYu=``4}0MC#SJ3W>lZd#a_u& zBr>_3U7b;T@_P0(Mv=*49O{gElkGTC+0=m=i!>*% Date: Thu, 23 Oct 2025 14:37:11 +0800 Subject: [PATCH 14/27] add 3461 --- javascript/LeetCode/String/3461.js | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 javascript/LeetCode/String/3461.js 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 From 4900559b939c6a2ebd4f8e7024cd888fbe592785 Mon Sep 17 00:00:00 2001 From: Mavis Date: Mon, 27 Oct 2025 15:11:52 +0800 Subject: [PATCH 15/27] add 1716 --- javascript/LeetCode/math/1716.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 javascript/LeetCode/math/1716.js 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 From dd9cef728d77d0797236b55dc78f0f5cacdea4e2 Mon Sep 17 00:00:00 2001 From: Mavis Date: Tue, 28 Oct 2025 14:46:00 +0800 Subject: [PATCH 16/27] add 3354 --- javascript/LeetCode/Array/3354.js | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 javascript/LeetCode/Array/3354.js 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 From c711d0bf6548f0c6d008dec52c7c7e95936b5deb Mon Sep 17 00:00:00 2001 From: Mavis Date: Wed, 29 Oct 2025 14:40:50 +0800 Subject: [PATCH 17/27] practice to solve codewars problem --- javascript/index.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/javascript/index.js b/javascript/index.js index f5e9b99..d7bccdd 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1047,3 +1047,24 @@ let numerator = 1, denominator = 2; // "0.5" // console.log(fractionToDecimal(numerator,denominator)); +function partlist(arr) { + // 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. + let result = []; + // 切成兩個元素 + // front多一個字,end則少一個字 + let front = arr[0]; + let original = arr.join(" "); + // console.log(original) + let inside = []; + for(let i = 0;i < arr.length;++i) { + + // inside[i] = original[i]; + // result.push(inside) + } + console.log(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 From c066026f5e5d4d41fbff9aa60d11220b5eae20d9 Mon Sep 17 00:00:00 2001 From: Mavis Date: Thu, 30 Oct 2025 14:19:20 +0800 Subject: [PATCH 18/27] add codewars problem solution --- javascript/codewar/array/16.js | 23 +++++++++++++++++++++++ javascript/index.js | 21 --------------------- 2 files changed, 23 insertions(+), 21 deletions(-) create mode 100644 javascript/codewar/array/16.js 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 d7bccdd..f5e9b99 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1047,24 +1047,3 @@ let numerator = 1, denominator = 2; // "0.5" // console.log(fractionToDecimal(numerator,denominator)); -function partlist(arr) { - // 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. - let result = []; - // 切成兩個元素 - // front多一個字,end則少一個字 - let front = arr[0]; - let original = arr.join(" "); - // console.log(original) - let inside = []; - for(let i = 0;i < arr.length;++i) { - - // inside[i] = original[i]; - // result.push(inside) - } - console.log(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 From 0d70de9eb19c6b43d30368436358afcf80e09541 Mon Sep 17 00:00:00 2001 From: Mavis Date: Fri, 31 Oct 2025 14:37:27 +0800 Subject: [PATCH 19/27] add practice --- javascript/LeetCode/Array/3289.js | 38 ++++++++++++++++++ javascript/index.js | 32 +++++++++++++++ python/index.py | 20 ++++++++- .../oop/__pycache__/Tortoise.cpython-312.pyc | Bin 2420 -> 2436 bytes 4 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 javascript/LeetCode/Array/3289.js 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/index.js b/javascript/index.js index f5e9b99..af8f38a 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1047,3 +1047,35 @@ let numerator = 1, denominator = 2; // "0.5" // console.log(fractionToDecimal(numerator,denominator)); + + +/** + * 3718. Smallest Missing Multiple of K + * + * 取得能被k整除且是所有能被k整除的最小數且不在nums中的元素並回傳 + * + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var missingMultiple = function(nums, k) { + let divisibleByK = []; + let ans = 0; + for(let i = 1;i <= 5;++i) { + divisibleByK.push(i*k); + } + for(let i = 0;i < divisibleByK.length;++i) { + if(!nums.includes(divisibleByK[i])){ + ans = divisibleByK[i]; + break; + } + } + return ans; +}; +// 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 +console.log(missingMultiple(nums,k)); \ No newline at end of file diff --git a/python/index.py b/python/index.py index c4ecf17..20b9e1a 100644 --- a/python/index.py +++ b/python/index.py @@ -26,8 +26,8 @@ from oop.Lion import Lion from oop.Behavior import move -greek = Tortoise("福氣",7,"veggie","地中海型陸龜") -greek.eat() +# greek = Tortoise("福氣",7,"veggie","地中海型陸龜") +# greek.eat() # greek.hibernation() # greek.environment() # greek.attack() @@ -267,3 +267,19 @@ def replaceDigits(s: str) -> str: # Output: "abcdef" # print(replaceDigits(s)) +def getSneakyNumbers(nums: List[int]) -> List[int]: + ''' + 3289. The Two Sneaky Numbers of Digitville + + 參數為數值陣列,回傳元素出現次數大於2的元素。回傳的陣列每個必須是唯一值 + ''' + ans = [] + + return ans +nums = [0,1,1,0] +# [0,1] +# print(getSneakyNumbers(nums)) + +a = int(input("2 numbers")) + +print("A is:",a) \ No newline at end of file diff --git a/python/oop/__pycache__/Tortoise.cpython-312.pyc b/python/oop/__pycache__/Tortoise.cpython-312.pyc index de922b05296bc2be3300d6206f32caafb4d10575..bfca32a238a2313c1d7d6fee449b22cdaee492c2 100644 GIT binary patch delta 97 zcmew&)FRA#nwOW00SK;?{K$yk$g9c3md=pExQKDG4U?(}(_E(2j38MC21bTT22Ex^ xP3FnPOh&@|K#?cAcD-CU@A<5jmy72=?_4=~2~!NGG*G;O;TFIDW`5>WHURnR96SI3 delta 81 zcmZn>{vyPCnwOW00SLr@earCO$g9c3mcp3Al+HBShDlY3c`nmxMvyE610zEvgC>jL h*T;R9eEYF Date: Mon, 3 Nov 2025 14:47:44 +0800 Subject: [PATCH 20/27] add 3718 --- javascript/LeetCode/Array/3718.js | 55 +++++++++++++++++++++++++++++++ javascript/index.js | 30 ----------------- 2 files changed, 55 insertions(+), 30 deletions(-) create mode 100644 javascript/LeetCode/Array/3718.js 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/index.js b/javascript/index.js index af8f38a..1a3a471 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1049,33 +1049,3 @@ let numerator = 1, denominator = 2; -/** - * 3718. Smallest Missing Multiple of K - * - * 取得能被k整除且是所有能被k整除的最小數且不在nums中的元素並回傳 - * - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var missingMultiple = function(nums, k) { - let divisibleByK = []; - let ans = 0; - for(let i = 1;i <= 5;++i) { - divisibleByK.push(i*k); - } - for(let i = 0;i < divisibleByK.length;++i) { - if(!nums.includes(divisibleByK[i])){ - ans = divisibleByK[i]; - break; - } - } - return ans; -}; -// 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 -console.log(missingMultiple(nums,k)); \ No newline at end of file From cd20b50f201f3c70c9d7c53cc7b24d77da71eff6 Mon Sep 17 00:00:00 2001 From: Mavis Date: Tue, 4 Nov 2025 14:05:51 +0800 Subject: [PATCH 21/27] 3318 not done --- javascript/index.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/javascript/index.js b/javascript/index.js index 1a3a471..13d2af2 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1049,3 +1049,31 @@ let numerator = 1, denominator = 2; +/** + * 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 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)); \ No newline at end of file From ddf0b90c47a209506f76d29828f3936945d6aefc Mon Sep 17 00:00:00 2001 From: Mavis Date: Wed, 5 Nov 2025 14:47:57 +0800 Subject: [PATCH 22/27] practice python --- python/index.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/python/index.py b/python/index.py index 20b9e1a..9fe6d1c 100644 --- a/python/index.py +++ b/python/index.py @@ -279,7 +279,3 @@ def getSneakyNumbers(nums: List[int]) -> List[int]: nums = [0,1,1,0] # [0,1] # print(getSneakyNumbers(nums)) - -a = int(input("2 numbers")) - -print("A is:",a) \ No newline at end of file From b47223e68317c9f64909843f23dd78d5e8639d6a Mon Sep 17 00:00:00 2001 From: Mavis Date: Thu, 6 Nov 2025 14:41:55 +0800 Subject: [PATCH 23/27] practice to solve problems in Python --- python/index.py | 15 +------------- python/leetcode/list/3289.py | 24 ++++++++++++++++++++++ python/leetcode/list/3467.py | 40 ++++++++++++++++++++++++++++++++++++ python/leetcode/list/3668.py | 22 ++++++++++++++++++++ 4 files changed, 87 insertions(+), 14 deletions(-) create mode 100644 python/leetcode/list/3289.py create mode 100644 python/leetcode/list/3467.py create mode 100644 python/leetcode/list/3668.py diff --git a/python/index.py b/python/index.py index 9fe6d1c..f532269 100644 --- a/python/index.py +++ b/python/index.py @@ -265,17 +265,4 @@ def replaceDigits(s: str) -> str: return res s = "a1c1e1" # Output: "abcdef" -# print(replaceDigits(s)) - -def getSneakyNumbers(nums: List[int]) -> List[int]: - ''' - 3289. The Two Sneaky Numbers of Digitville - - 參數為數值陣列,回傳元素出現次數大於2的元素。回傳的陣列每個必須是唯一值 - ''' - ans = [] - - return ans -nums = [0,1,1,0] -# [0,1] -# print(getSneakyNumbers(nums)) +# print(replaceDigits(s)) \ 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 From 4c0685c95ff6cb61a679331dab32f556720034e2 Mon Sep 17 00:00:00 2001 From: Mavis Date: Mon, 10 Nov 2025 14:47:37 +0800 Subject: [PATCH 24/27] add practice in JS --- javascript/LeetCode/Array/3542.js | 38 +++++++++++++++++++++++++++++++ javascript/index.js | 38 +++++++++++++++++++++++++++++-- 2 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 javascript/LeetCode/Array/3542.js 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/index.js b/javascript/index.js index 13d2af2..5e4ae12 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1071,9 +1071,43 @@ var findXSum = function(nums, k, x) { } }; -let nums = [1,1,2,2,3,4,2,3], k = 6, x = 2; +// 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)); \ No newline at end of file +// console.log(findXSum(nums,k,x)); + + +/** + * 2169. Count Operations to Obtain Zero + * + * 一次操作中,若nums1 >= nums2,則nums1 = nums1 - nums2,否則nums2 = nums1 - nums2 + * 計算要幾次才能使得nums1 = 0 or num2 = 0 + * + * @param {number} num1 + * @param {number} num2 + * @return {number} + */ +var countOperations = function(num1, num2) { + let ans = 0; + while(num1 !== 0 || num2 !== 0){ + if(num1 > num2){ + num1 = num1 - num2; + ans++; + }else{ + num2 = num1 - num2; + ans++; + } + } + 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 From 2b1cb32fe83c56491df49512611840a5a885e971 Mon Sep 17 00:00:00 2001 From: Mavis Date: Tue, 11 Nov 2025 14:26:39 +0800 Subject: [PATCH 25/27] add 2169 --- javascript/LeetCode/Array/2169.js | 42 +++++++++++++++++++++++++++++++ javascript/index.js | 32 ----------------------- 2 files changed, 42 insertions(+), 32 deletions(-) create mode 100644 javascript/LeetCode/Array/2169.js 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/index.js b/javascript/index.js index 5e4ae12..1d00f6c 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1079,35 +1079,3 @@ var findXSum = function(nums, k, x) { // console.log(findXSum(nums,k,x)); -/** - * 2169. Count Operations to Obtain Zero - * - * 一次操作中,若nums1 >= nums2,則nums1 = nums1 - nums2,否則nums2 = nums1 - nums2 - * 計算要幾次才能使得nums1 = 0 or num2 = 0 - * - * @param {number} num1 - * @param {number} num2 - * @return {number} - */ -var countOperations = function(num1, num2) { - let ans = 0; - while(num1 !== 0 || num2 !== 0){ - if(num1 > num2){ - num1 = num1 - num2; - ans++; - }else{ - num2 = num1 - num2; - ans++; - } - } - 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 From 67744e92cbf8466fe38f8cc0f4e8e56a6624e4f1 Mon Sep 17 00:00:00 2001 From: Mavis Date: Wed, 12 Nov 2025 14:12:47 +0800 Subject: [PATCH 26/27] practice to slove a problem --- javascript/index.js | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/javascript/index.js b/javascript/index.js index 1d00f6c..077741b 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1061,21 +1061,27 @@ let numerator = 1, denominator = 2; * @return {number[]} */ var findXSum = function(nums, k, x) { - // 將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 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; +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)); - - +console.log(findXSum(nums,k,x)); \ No newline at end of file From eb2f2062deec8a8abd458c1c8884346cb38ebcdd Mon Sep 17 00:00:00 2001 From: Mavis Date: Thu, 13 Nov 2025 14:27:45 +0800 Subject: [PATCH 27/27] add 2654 --- javascript/LeetCode/math/2654.js | 59 ++++++++++++++++++++++++++++++++ javascript/index.js | 5 +-- 2 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 javascript/LeetCode/math/2654.js 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/index.js b/javascript/index.js index 077741b..2d5a115 100644 --- a/javascript/index.js +++ b/javascript/index.js @@ -1079,9 +1079,10 @@ var findXSum = function(nums, k, x) { // } }; -let nums = [1,1,2,2,3,4,2,3], k = 6, x = 2; +// 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)); \ No newline at end of file +// console.log(findXSum(nums,k,x)); +