【python3】leetcode 169. Majority Element (easy)
阿新 • • 發佈:2018-12-12
Given an array of size n, find the majority element. The majority element is the element that appears more than
⌊ n/2 ⌋
times.You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
我的思路:
這道題很簡單 也有各種很簡單的方法寫,所以我自己在思考有沒有突破點
題目說majority element的數量一定大於 [n/2] (向下取整),所以排序後的 [n/2]一定是majority element
class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return nums[int(len(nums)/2)]
不過我看了discussion大家都是這種方法哈哈哈所以思維都差不多嘛~~