精華區beta Marginalman 關於我們 聯絡資訊
第一題 Number of Bit Changes to Make Two Integers Equal ## 思路 掃32bit, 如果k的bit為0,n的bit為1 回傳-1 如果k的bit為1,n的bit為0 change+1 ## Code ```python class Solution: def minChanges(self, n: int, k: int) -> int: ans = 0 for i in range(32): if n & 1 and k & 1 == 0: ans += 1 if n & 1 == 0 and k & 1: return -1 n >>= 1 k >>= 1 return ans ``` 第二題 Vowels Game in a String ## 思路 計算vowels數量, 奇數個 - Alice直接獲勝 偶數個 - 刪掉奇數個vowels會剩下三種Case: bab / ba / a, 也都會是Alice獲勝 所以只有零個的時候會是False ## Code ```python class Solution: def doesAliceWin(self, s: str) -> bool: vowels = {'a', 'e', 'i', 'o', 'u'} count = 0 for ch in s: if ch in vowels: count += 1 if count == 0: return False return True ``` 第三題 Maximum Number of Operations to Move Ones to the End ## 思路 由左往右掃, 紀錄1的個數ones 每次遇到0的時候就移動ones個1 (重複0時略過) ## Code ```python class Solution: def maxOperations(self, s: str) -> int: n = len(s) ans = ones = 0 i = 0 for i in range(n): if i and s[i] == s[i-1] == '0': continue if s[i] == '0': ans += ones else: ones += 1 return ans ``` 第四題 Minimum Operations to Make Array Equal to Target ## 思路 如果 diff[1:3] > 0 而 diff[3] <= 0 的時候 只會對nums[1:3] 做Increment, 對nums[3:??] 做Decrement 在nums[1:3]範圍內就是加上diff差值 ## Code ```python class Solution: def minimumOperations(self, nums: List[int], target: List[int]) -> int: n = len(nums) diff = [n-t for n, t in zip(nums, target)] ans = abs(diff[0]) for i in range(1, n): if diff[i] * diff[i-1] <= 0: ans += abs(diff[i]) else: ans += max(abs(diff[i]) - abs(diff[i-1]), 0) return ans ``` -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.221 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1721534741.A.ACA.html
sustainer123: 大師 07/21 12:08
oin1104: 大師 07/21 12:21
DJYOSHITAKA: 大師... 第四題肥肥直接放棄 07/21 12:41