Majority Element

来源:互联网 发布:非农历史数据统计 编辑:程序博客网 时间:2024/06/09 21:10

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.

  1. 找到数组中出现次数大于n/2的项;
  2. 可以先给数组排序,如果出现次数多余一半,则排序后中间一定为该项;
class Solution {public:    int majorityElement(vector<int>& nums) {      sort(nums.begin(),nums.end());      int n = nums.size();      return nums[n/2];    }};
  1. 第二种采用分治的思想;
  2. 分为左右两组,一次递归选出出现次数多的
class Solution {public:    int majorityElement(vector<int>& nums) {        return majority(nums, 0, nums.size() - 1);    }private:    int majority(vector<int>& nums, int left, int right) {        if (left == right) return nums[left];        int mid = left + ((right - left) >> 1);        int lm = majority(nums, left, mid);        int rm = majority(nums, mid + 1, right);        if (lm == rm) return lm;        return count(nums.begin() + left, nums.begin() + right + 1, lm) > count(nums.begin() + left, nums.begin() + right + 1, rm) ? lm : rm;    }}; 
0 0
原创粉丝点击