46. Majority Element
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
Given [1, 1, 1, 1, 2, 2, 2], return 1
Challenge
O(n) time and O(1) extra space
方法1:直接排序找中位数就可以
class Solution {
public:
/*
* @param nums: a list of integers
* @return: find a majority number
*/
int majorityNumber(vector<int> &nums) {
// write your code here
sort(nums.begin(),nums.end());
int numSize = nums.size();
return nums.at(numSize/2);
}
};

本文介绍了一种寻找数组中出现次数超过一半的元素的方法。通过排序找到中位数即可确定该元素,这种方法的时间复杂度为O(n),空间复杂度为O(1)。

4125

被折叠的 条评论
为什么被折叠?



