多味的LeetCode --- 面试题 17.10. 主要元素

前期回顾:

面试题39. 数组中出现次数超过一半的数字

题目描述:

数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-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

解题思路:

  1. 将数组中元素的种类以及数量用字典表示出来 —> Counter;
  2. 依次判断相应元素的数量是否满足条件即可。

代码:

class Solution:
    def majorityElement(self, nums):
        from collections import Counter
        words = Counter(nums)
        for word in words.items():
            if word[1] > len(nums)//2:
                return word[0]
        return -1

s = Solution()
nums = [3,2]
print(s.majorityElement(nums))

题目来源:

https://leetcode-cn.com/problems/find-majority-element-lcci

猜你喜欢

转载自blog.csdn.net/weixin_43283397/article/details/112861350
今日推荐