精華區beta Marginalman 關於我們 聯絡資訊
3217. Delete Nodes From Linked List Present in Array ## 思路 先把nums轉成set 掃linked list時, 如果下一個node的值在set裡面就跳過去 ## Code ```python class Solution: def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]: nums = set(nums) dummy = ListNode(-1, head) curr = dummy while curr.next: if curr.next.val not in nums: curr = curr.next else: curr.next = curr.next.next return dummy.next ``` -- 640. Solve the Equation ## 思路 parse字串的方式跟前幾天的每日差不多 但要注意x跟0x的case 用兩個變數存 x 跟 value 的值, '='左右邊的+-要反過來 最後檢查無解/無限解 並處理1x, -ax 除gcd ## Code ```python class Solution: def solveEquation(self, equation: str) -> str: def get_gcd(x, y): while y: x, y = y, x % y return x def parse_val(i, is_left): is_x = is_neg = False if equation[i] == '+': i += 1 elif equation[i] == '-': is_neg = True i += 1 num = 0 while i < len(equation): if equation[i].isdigit(): num = num * 10 + int(equation[i]) i+=1 elif equation[i] == 'x': if num == 0 and (i == 0 or equation[i-1] in {'+', '-', '='}): num = 1 is_x = True i+=1 else: break if is_neg: num = -num if is_x: res[0] += num * (1 if is_left else -1) else: res[1] += num * (-1 if is_left else 1) return i i, n = 0, len(equation) res = [0, 0] is_left = True while i < n: i = parse_val(i, is_left) if i < n and equation[i] == '=': is_left = False i += 1 if res[0] == 0: if res[1] == 0: return 'Infinite solutions' return 'No solution' gcd = get_gcd(res[0], res[1]) res[0] //= gcd res[1] //= gcd if res[0] < 0: res[0], res[1] = -res[0], -res[1] if res[0] == 1: return f'x={res[1]}' return f'{res[0]}x={res[1]}' ``` -- https://i.imgur.com/kyBhy6o.jpeg -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.188 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1725603785.A.E04.html
sustainer123: 大師 09/06 14:26
oin1104: 大師 09/06 14:27
DJYOMIYAHINA: 別捲了 09/06 14:29