首先是 15. 3Sum (medium)
https://leetcode.com/problems/3sum/
三個三個一組,找出所有可以和為0的組合。
因為這題在寫時需要整理,我把想法放程式裡
class Solution:
#給一個數列尋找三數和可以變成0
#會出現相同的數字
#暴力法失敗
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
# boolTable = [True]*len(nums)
zeroTable = set()
for i in range(len(nums)):
for j in range(i,len(nums)):
if i != j:
for k in range(j,len(nums)):
if k != i and k != j:
temp = 1
if nums[i]+nums[j]+nums[k] == 0:
zeroTable.add((nums[i],nums[j],nums[k]))
return zeroTable
def threeSum(self, nums: List[int]) -> List[List[int]]:
#分成正負整數&&zero
negative,positive,zero = [],[],[]
for i in nums:
if i<0:
negative.append(i)
elif i>0:
positive.append(i)
else:
zero.append(0)
#在tuple那邊就不需要再排序
negative.sort()
positive.sort()
#靠,這邊不用set會被搞死
nS = set(negative)
pS = set(positive)
#分成三個部分處理
#1. 含有一個0 && 三個0
#2. 二個負數一個正數
#3. 二個正數一個負數
ans = set()
pL,nL = len(positive),len(negative)
#處理0
if zero:
for i in positive:
if -i in negative:
ans.add((-i, 0, i))#按照大小排好,到時候要搞重複值比較簡單
if len(zero) > 2:
ans.add((0,0,0))
#二個負數一個正數
for i in range(nL):
for j in range(i+1,nL):
if -(negative[i]+negative[j]) in pS:
ans.add((negative[i],negative[j],-(negative[i]+negative[j])))
#二個正數一個負數
for i in range(pL):
for j in range(i+1,pL):
if -(positive[i]+positive[j]) in nS:
ans.add((-(positive[i]+positive[j]),positive[i],positive[j]))
return ans
再來是 1002. Find Common Characters (easy)
https://leetcode.com/problems/find-common-characters/
給多個字串,給所有字串共同有的字母(包含重複的)
想法:
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
wordsCounter = [Counter(i) for i in words]
ans = []
for i in wordsCounter[0]:
temp = wordsCounter[0][i]
flag = 1
for j in wordsCounter[1:]:
if i not in j:
flag = 0
break
else:
temp = min(temp,j[i])
if flag:
ans += [i]*temp
return ans
再來是 997. Find the Town Judge (easy)
https://leetcode.com/problems/find-the-town-judge/
找出法官,給多個數對[a,b],代表a信任b
法官必不信任人,所有人必信任法官,回傳法官,無則回傳-1
class Solution:
#後面的人代表被信任的人
#所有人都信任他就代表他是法官
#1. 只要有一人不信任就不是
#2. 法官信任其他人也不行
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if n == 1:
return 1
if (n>1 and len(trust)<n-1):
return -1
temp = list(zip(*trust))
tC = Counter(temp[1])#法官一定會被最多人信任
judge = 0
for i in tC:
if tC[i]>tC[judge]:
judge = i
if judge in temp[0] or tC[judge] != n-1:#法官不可能信任人,信任法官的會剛好n-1人
return -1
return judge
#別人的寫法
def findJudge(self, n: int, trust: List[List[int]]) -> int:
trusted = [0] * (n) #鎮上有 n 個人
for a, b in trust:
trusted[a-1] = -1 #投票給法官的人,擾亂統計數據
trusted[b-1] += 1 #被投票的人
if n-1 in trusted:
return trusted.index(n-1)+1 #別忘記自編的編號有少1
return -1
以上為今天的練習,感謝大家