[Lintcode]46. Majority Element/[Leetcode]169. Majority Element

本文详细解析了LeetCode上编号169的题目——Majority Element的解决方案。该题目标是在给定整数数组中找到出现次数超过一半的多数元素。文章提供了Python实现的代码示例,采用排序算法确定多数元素,同时讨论了时间复杂度为nlog(n)的解决策略。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值