原题是:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
思路是:
出现超过一半次数的数,一定是经过排序后,占据中间位置的那个数。
代码是:
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sortNums = sorted(nums)
midIndex = int(len(nums)/2)
return sortNums[midIndex]
学到:
1.python取整,如果用math.ceil, math.floor,返回的是float类型

2.本题向下取整,直接使用了int().经过测试,本题的话,使用math.floor也一样可以通过。
网友评论