美文网首页
Leetcode 169. Majority Element

Leetcode 169. Majority Element

作者: 岛上痴汉 | 来源:发表于2017-09-13 08:47 被阅读0次

原题地址: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<int>& nums) {
        sort(nums.begin(),nums.end());
        return nums[nums.size()/2];
    }
};

相关文章

网友评论

      本文标题:Leetcode 169. Majority Element

      本文链接:https://www.haomeiwen.com/subject/gucksxtx.html