class
solution
(object):
deflongestmountain
(self, a)
:"""
:type a: list[int]
:rtype: int
"""# 想法:乙個用來記錄左邊山底,乙個用來記錄山頂,乙個用來記錄右邊山底
left=
0 top=left
right=top
maxlength=
0while
(left<
len(a)-2
):length=
0# 首先找到左邊山底
for i in
range
(left,
len(a)-1
):if(a[i]
):left=i
break
# 找到山頂
top=left
while
(top<
len(a)-1
and a[top]
):top=top+
1#找到右邊山底
right=top
while
(right<
len(a)-1
and a[right]
>a[right+1]
):right=right+
1# 山脈長度
if(right>top and top>left)
: length = right - left+
1 left=right
else
: left=right+1if
(length>maxlength)
: maxlength=length
# 但是可能存在多個山脈
return maxlength
偷懶了兩天,這個**效果不太好,明天再學習一下別人的解法,要考試了,加油複習啊,向著學弟衝啊
更簡潔的寫法:
class
solution
(object):
deflongestmountain
(self, a)
:"""
:type a: list[int]
:rtype: int
"""end=base=
0 length=
0while
(base<
len(a)-2
):end=base
if(end+
1<
len(a)
and a[end]
):while
(end+
1<
len(a)
and a[end]
):end+=
1# 找到山頂,end不斷向前移動
if(end+
1<
len(a)
and a[end]
>a[end+1]
):# 要先判斷有下山的過程
while
(end+
1<
len(a)
and a[end]
>a[end+1]
):end+=
1# 找到右邊山腳,end不斷向前移動
length=
max(length,end-base+1)
# 寫在有下山的條件裡面
base=
max(end,base+1)
return length
還有一種想法是,先找到山頂,往兩邊找山腳
class
solution
(object):
deflongestmountain
(self, a)
:"""
:type a: list[int]
:rtype: int
"""length=
0for i in
range(1
,len
(a)-1)
:if(a[i]
>a[i-1]
and a[i]
>a[i+1]
):left=i-
1 right=i+
1while
(left>
0and a[left]
>a[left-1]
):left-=
1while
(right<
len(a)-1
and a[right]
>a[right+1]
):right+=
1 length=
max(length,right-left+1)
return length
執行效率 3>2>1 LeetCode 845 陣列中的最長山脈
我們把陣列 a 中符合下列屬性的任意連續子陣列 b 稱為 山脈 b.length 3 存在 0 i b.length 1 使得 b 0 b 1 b i 1 b i b i 1 b b.length 1 注意 b 可以是 a 的任意子陣列,包括整個陣列 a。給出乙個整數陣列 a,返回最長 山脈 的長度...
leetcode 845 陣列中的最長山脈
注意 b可以是a的任意子陣列,包括整個陣列a 給出乙個整數陣列a,返回最長 山脈 的長度。若無則返回0 示例1 輸入 2,1,4,7,3,2,5 輸出 5 最長的 山脈是 1,4,7,3,2 示例2 輸入 2,2,2 輸出 0 不含 山脈 陣列長度不超過1000 int longestmountai...
845 陣列中的最長山脈LeetCode
陣列中的最長山脈 題目描述提示幫助提交記錄社群討論閱讀解答 隨機一題 我們把陣列 a 中符合下列屬性的任意連續子陣列 b 稱為 山脈 b.length 3 存在 0 i b.length 1 使得 b 0 b 1 b i 1 b i b i 1 b b.length 1 注意 b 可以是 a 的任意...