python 求眾數(shù) LeetCode N0.169
這道題有很多解法官方leetcode上面是六種,由于說的太過于詳細(xì),我都不好意思,再補(bǔ)充什么了。所以我就寫了一點(diǎn),沒看答案之前的寫法,和我覺得,需要掌握的寫法吧。他寫的很多代碼很精簡(jiǎn),值得學(xué)習(xí)。(ps,納悶的是,即使我用的O(n)的復(fù)雜度,排名也很靠后哈哈哈哈哈)
class
Solution
(
object
)
:
def
majorityElement
(
self
,
nums
)
:
"""
:type nums: List[int]
:rtype: int
"""
#count = 0
#candidate = None
#for num in nums:
# if count == 0:
# candidate = num
# count += (1 if num == candidate else -1)
#return candidate
count
=
0
candidate
=
nums
[
0
]
for
i
in
range
(
len
(
nums
)
)
:
if
nums
[
i
]
==
candidate
:
count
+=
1
else
:
count
-=
1
if
count
==
0
:
candidate
=
nums
[
i
+
1
]
return
candidate
class
Solution
(
object
)
:
def
majorityElement
(
self
,
nums
)
:
"""
:type nums: List[int]
:rtype: int
"""
import
math
count
=
{
}
if
len
(
nums
)
%
2
==
1
:
n
=
len
(
nums
)
+
1
else
:
n
=
len
(
nums
)
for
i
in
nums
:
count
[
i
]
=
count
.
get
(
i
,
0
)
+
1
if
count
[
i
]
>=
n
/
2
:
return
i
for
i
in
nums
:
if
count
[
i
]
>=
n
/
2
:
return
i
class
Solution
:
def
majorityElement
(
self
,
nums
)
:
counts
=
collections
.
Counter
(
nums
)
return
max
(
counts
.
keys
(
)
,
key
=
counts
.
get
)
#作者:LeetCode
#鏈接:https://leetcode-cn.com/problems/majority-element/solution/qiu-zhong-shu-by-leetcode-2/
#來源:力扣(LeetCode)
#著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
