python 求眾數 LeetCode N0.169
這道題有很多解法官方leetcode上面是六種,由于說的太過于詳細,我都不好意思,再補充什么了。所以我就寫了一點,沒看答案之前的寫法,和我覺得,需要掌握的寫法吧。他寫的很多代碼很精簡,值得學習。(ps,納悶的是,即使我用的O(n)的復雜度,排名也很靠后哈哈哈哈哈)
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)
#著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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