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); } };