首页 > 其他 > 详细

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

时间:2019-02-10 18:55:11      阅读:180      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/siriusli/p/10359939.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!