先說感言:
我認為這三十天內最麻煩的不是每天勤分不懈的寫題目,而是寫一篇可以給人看得懂的文章(好啦,我知道有部份我寫得有點潦草),題目基本上就算沒有鐵人賽,我也會每天做,我打算持續一年左右的時間,畢竟手感是要建立的,之前荒廢多久,就用多少時間來還,要不然怎好意思教人呢?總之,我堅持住了QQ
首先 2095. Delete the Middle Node of a Linked List (medium)
https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/
Linked List 基本題,刪除中間的Node點。
一開始想法很簡單,先跑一遍整個Linked List,再跑一次到中間即可。
但後來就想到,在寫 Circular Linked List時會用到 Floyd(龜兔賽跑演算法),因此後來又補上此種寫法。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
#普通寫法
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next is None:
return None
ans = temp = head
count = 0
while head:
head = head.next
count+=1
mid = (count//2)
while mid-1:
temp = temp.next
mid-=1
temp.next = temp.next.next
return ans
#勿忘龜兔賽跑
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next is None:
return None
slow = fast = ans = head
fast = fast.next
while fast and fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
slow.next = slow.next.next
return ans
再來是 389. Find the Difference (easy)
https://leetcode.com/problems/find-the-difference/
給兩個字串 s,t ,t會比s多一個字母,要找出是哪個字母。
想法,一開始想用set()但後來發現,有可能會有重複的,因此使用Counter,直接找出哪一種多了一個。
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
sC = Counter(s)
tC = Counter(t)
for i in tC:
if i not in sC:
return i
elif sC[i] != tC[i]:
return i
再來是 326. Power of Three (easy)
https://leetcode.com/problems/power-of-three/
給一個整數n,確認是否為3的x次方。
想法有兩個
第一種方法就是一直除3,只要有小數點就88
第二種直接運用高中數學的log判斷,log(n)/log(3)必整除
import math
class Solution:
#感覺可以出給學生寫(while迴圈的地方)
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
if n != 1 and n<3:
return False
while n > 1:
n /= 3
return True if n == int(n) else False
#不用loop的寫法
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
#不能顛倒,否則log(0)沒東西
return n > 0 and math.log10(n)/math.log10(3) % 1 == 0
以上為今天的練習,感謝大家