1.问题描述
给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例
输入:nums = [3,2,3]
输出:3
输入:nums = [2,2,1,1,1,2,2]
输出:2
2.分析
还是老样子,一看到首先就是暴力解决。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
label=1
nums.sort()
if len(nums)==1:
return nums[0]
for i in range(len(nums)):
if nums[i]==nums[i-1]:
label+=1
if label>(len(nums)/2):
return nums[i]
break
else:
continue
label=1
执行结果:通过 显示详情 添加备注
执行用时: 28 ms, 在所有 Python 提交中击败了 56.18%
的用户
内存消耗: 15.1 MB, 在所有 Python 提交中击败了 17.37%的用户
通过测试用例: 43 / 43
后来又思考了一下,既然是返回一个在数组中能占超过一半的数,那如果我将这个数组排序,中间的那个必然就是我要找的。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
label=1
nums.sort()
return(nums[int(len(nums)/2)])
执行结果:
通过
显示详情
添加备注
执行用时:32 ms, 在所有 Python 提交中击败了38.04%的用户
内存消耗:14 MB, 在所有 Python 提交中击败了90.03%的用户
通过测试用例:43 / 43