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)
原文地址:https://www.cnblogs.com/siriusli/p/10359939.html
时间: 2024-10-25 01:07:24