高階程式設計技術hw week8

2021-08-19 08:04:44 字數 1280 閱讀 1728

leetcode #11 container with most water

**如下:

class solution:

def maxarea(self, height):

""":type height: list[int]

:rtype: int

"""maxwater=0

i=0j=len(height)-1

while i解題思路:

我一開始想當然的直接用了兩層迴圈,窮舉所有可能性尋找最大值。然後毫無疑問地超時了。於是開始思考時間複雜度更低的演算法。之前是從左邊開始,固定一端,迴圈另一端尋找最大值,而這樣顯然太沒效率,因此考慮兩端同時移動。而又因為在選定的兩條線中,能夠決定水容量多少的是較短的一根,所以在初始狀態選擇最邊緣的兩根線後,向中間移動時只需要判斷兩根的長度,保留較長的那根線,然後用乙個變數來記錄移動過程中所能裝下水的最大值。這樣移動只能保證在每次移動後,所取到的是接下來更有可能裝水容量增加的選擇,而通過比較之前記錄下的最大值與此次的值,在迴圈結束時保留下來的就是最大值。

leetcode #38 count and say

**如下:

class solution:

def countandsay(self, n):

""":type n: int

:rtype: str

"""s='1'

for i in range(1,n):

temp=s[0]

new_s=''

times=1

for j in range(1,len(s)):

if s[j]==temp:

times=times+1

else:

new_s=new_s+str(times)+str(temp)

temp=s[j]

times=1

new_s=new_s+str(times)+str(temp)

s=new_s

return s

解題思路:

這道題一開始讓我有些困擾的是沒有讀懂題意,後來仔細看了一下說明,才明白這些序列每乙個都是按照給定讀法讀取上乙個的結果。所以只需要按照給定的讀法來編寫程式。由於要取得第n個序列,而前面n-1個都不再需要,所以我採用的方法是根據序列中的上乙個字串得到下乙個,然後就將新的替代掉原先的,從而迴圈得到結果。而得到下一字串的方法,則是乙個乙個讀取字串中的字元,有相同的則次數加一,沒有則將這一段所讀到的字元和次數加入新字串中。

高階程式設計技術hw week9

leetcode 67 add binary 如下 class solution def addbinary self,a,b type a str type b str rtype str if len a len b for i in range len a len b b 0 b l len ...

高階程式設計技術作業 8

題目描述 編寫乙個迴圈,提示使用者輸入一系列的比薩配料,並在使用者輸入 quit 時結束迴圈。每當 使用者輸入一種配料後,都列印一條訊息,說我們會在比薩中新增這種配料。input potato tomato fish quit output please input an ingredient we...

高階程式設計技術作業 5

題目描述 使用乙個for迴圈列印數字1 20 包含 展示 for number in range 1,21 print number input null output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 題目描述 通過給函式rang...