﻿ python 求众数 LeetCode N0.169 - 军军小站|张军博客

# python 求众数 LeetCode N0.169

```            ```

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）

#著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

```
```

QQ号联系： 360901061

【本文对您有帮助就好】