面试题 17.10. 主要元素
面试题 17.10. 主要元素
数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
示例 1:
输入:[1,2,5,9,5,9,5,5,5]
输出:5
示例 2:
输入:[3,2]
输出:-1
示例 3:
输入:[2,2,1,1,1,2,2]
输出:2
说明:
你有办法在时间复杂度为 O(N),空间复杂度为 O(1) 内完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-majority-element-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1、偷鸡解
class Solution:
def majorityElement(self, nums: List[int]) -> int:
length=len(nums)
import collections
result=collections.Counter(nums)
if result.most_common()[0][1]>length/2:
return result.most_common()[0][0]
else:
return -1
2、摩尔投票法确定majority,再遍历确定是否大于一半数量,时间复杂度2n,O(n)满足条件
#数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
class Solution:
# def majorityElement(self, nums: List[int]) -> int:
def majorityElement( nums):
length=len(nums)
probe=0
for i in range(length):
# print(probe)
if probe==0:
now_nums=nums[i]
if nums[i]==now_nums:
probe=probe+1
else:
probe=probe-1
if probe==0:
return -1
now_nums_id=0
for i in range(length):
if nums[i]==now_nums:
now_nums_id+=1
if now_nums_id>length/2:
return now_nums
else:
return -1
nums=[1,2,5,9,5,9,5,5,5]
result=Solution.majorityElement(nums)
print(result)
3、如果存在主要元素,那么排序后,中间那个值一定是主要元素
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
length=len(nums)
out=nums[int(length/2)]
prob=0
for i in range(length):
if nums[i]==out:
prob=prob+1
if prob>length/2:
return out
else:
return -1

浙公网安备 33010602011771号