LeetCode:Majority Element
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.
解决思路:
找到不同的两个元素之后就同时“删除”这两个元素,最后剩下的哪个就是majority element
我用python 做的:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result =0
counter = 0
for i in nums:
if counter ==0:
result = i
counter =1
elif i ==result:
counter+=1
else :
counter-=1
return result
本文介绍了一种解决LeetCode Majority Element问题的有效方法。通过遍历数组并利用抵消思想来找出出现次数超过一半的多数元素。这种方法巧妙地避免了排序和额外空间开销。
5478

被折叠的 条评论
为什么被折叠?



