码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-02-10 19:03:48      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:top   pytho   思路   https   www.   msm   extra   number   lint   

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

标签:top   pytho   思路   https   www.   msm   extra   number   lint   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!