首先是 118. Pascal's Triangle (easy)
https://leetcode.com/problems/pascals-triangle/
簡單來說,輸入一個數字n,要製造一個n層的帕斯卡三角形
想法:
1.因為左右必為1,所以製造temp2到時候用插的
2.用迭代的方式把兩個數字相加插入
class Solution:
#感覺可以用數學公式寫(但後來沒用)
#怪了怎麼比我想像的還快zzzzzz
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 1:
return [[1]]
elif numRows == 2:
return [[1],[1,1]]
result = [[1],[1,1]]
r = 3
while r <= numRows:
temp1 = result[-1]
temp2 = [1,1]
a = -1
for i in range(r-2):
a = temp1[-1-i]
b = temp1[-2-i]
temp2.insert(1,a+b)
result.append(temp2)
r += 1
return result
稍微改了一下寫法
#另外一種寫法,其實我原本是這樣想的,從前面來做,只是不知道為啥最後偏了XDD
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 1:
return [[1]]
result = [[1], [1,1]]
for i in range(2, numRows):
LL = sol[row - 1]
temp = [1]
for j in range(1,len(LL)):
temp.append(LL[j-1] + LL[j])
temp.append(1)
result.append(temp)
return sol
再來是 119. Pascal's Triangle II (easy)
https://leetcode.com/problems/pascals-triangle-ii/
老實說真的今天太累的才來寫這種偷懶的題目.....
答案跟118幾乎一樣,只要回傳最後一項就好
其實可以優化,根本不用這麼大的空間儲存,只要留下兩個list就好
class Solution:
#直接複製118. Pascal's Triangle,不是啊這根本一樣的題目阿==
#老實說可以優化
def getRow(self, numRows: int) -> List[int]:
if numRows == 0:
return [1]
elif numRows == 1:
return [1,1]
result = [[1],[1,1]]
r = 2
while r <= numRows:
temp1 = result[-1]
temp2 = [1,1]
a = -1
for i in range(r-1):
a = temp1[-1-i]
b = temp1[-2-i]
temp2.insert(1,a+b)
result.append(temp2)
r += 1
return result[-1]
再來是 136. Single Number(easy)
https://leetcode.com/problems/single-number/
給一個非空數列,找出裡面唯一單獨的數字,輸出該數字位置
想法
1.找出唯一單獨的數字
2.找出該數字的位置
但基本上,這題寫法很多,可以自由發揮,最簡單易懂的應該是Counter
class Solution:
#python超級白癡做法
def singleNumber(self, nums: List[int]) -> int:
n_nums = list(set(nums))
nums2 = nums.copy()
for i in n_nums:
nums2.remove(i)
for i in nums:
if i not in nums2:
return i
#python超級白癡做法2 TLE
def singleNumber(self, nums: List[int]) -> int:
for i in nums:
if nums.count(i) == 2:
nums[nums.index(i)] = None
nums[nums.index(i)] = None
for i in nums:
if not i is None:
return i
#python超級白癡做法3
def singleNumber(self, nums: List[int]) -> int:
rec = []
for i in range(len(nums)):
if nums[i] not in nums[i+1:] and nums[i] not in rec:
return nums[i]
else:
rec.append(nums[i])
#使用Counter:可以計算每個List東西有幾個,並化為字典 #最快
def singleNumber(self, nums: List[int]) -> int:
d = Counter(nums)
for i in d:
if d[i] == 1:
return i
#使用Xor,神奇的寫法
def singleNumber(self, nums: List[int]) -> int:
c = 0
for i in nums:
c ^= i
return c
#使用lambda加上xor
def singleNumber(self, nums: List[int]) -> int:
return reduce(lambda total, el: total ^ el, nums)
以上就是今天的練習,謝謝大家