[Lintcode]46. Majority Element/[Leetcode]169. Majority Element
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]46. Majority Element/[Leetcode]169. Majority Element相关的知识,希望对你有一定的参考价值。
46. Majority Element/[169. Majority Element(https://leetcode.com/problems/majority-element/)
- 本题难度: Easy
- Topic: Greedy
Description
Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.
Example
Example1:
Given [1, 1, 1, 1, 2, 2, 2], return 1
Example2:
Given [1, 1, 1, 2, 2, 2, 2], return 2
Challenge
O(n) time and O(1) extra space
Notice
You may assume that the array is non-empty and the majority number always exist in the array.
我的代码
class Solution:
"""
@param: nums: a list of integers
@return: find a majority number
"""
def majorityNumber(self, nums):
# write your code here
nums.sort()
return nums[len(nums)//2]
思路
超过了1/2,所以最中间的元素肯定是决定最多元素
- 时间复杂度 nlog(n)
以上是关于[Lintcode]46. Majority Element/[Leetcode]169. Majority Element的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Majority Number III
[LintCode] Majority Number 求众数