Leetcode 169. Majority Element

原题地址:https://leetcode.com/problems/majority-element/description/

题目描述

169.Majority Element
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.
在保证题目所给的一串元素里出现次数最多的元素的次数大于⌊ n/2 ⌋的情况下,找到这个元素。

思路

我的思路很简单,就是先排序,然后因为题目保证了元素的出现次数大于⌊ n/2 ⌋,所以排完序以后在⌊ n/2 ⌋这个位置的元素就是目标元素。

代码

class Solution {
public:
    int majorityElement(vector& nums) {
        sort(nums.begin(),nums.end());
        return nums[nums.size()/2];
    }
};

你可能感兴趣的:(Leetcode 169. Majority Element)