[leetcode] 169. Majority Element 解题报告

题目链接:https://leetcode.com/problems/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.

思路:本题有两种方法:

1.基于快速排序的分割算法,partition函数每次会把数组分成两个部分,并把一个值排在正确的位置,如果这个位置是在n/2处,则说明这个数必然是出现超过n/2次的数。这种方 法同样可以处理寻找第K大的数。

代码如下:

class Solution {
public:
    int partition(vector<int>& nums, int begin, int end){
        int value = nums[begin];
        while(begin < end){
            while(begin < end && value < nums[end])
                end--;
            if(begin < end)
                nums[begin++] = nums[end];
            while(begin < end && value > nums[begin])
                begin++;
            if(begin < end)
                nums[end--] = nums[begin];
        }
        nums[begin] = value;
        return begin;
    }
    int majorityElement(vector<int>& nums) {
        int start = 0;
        int end = nums.size() -1;
        int index = partition(nums, start, end);
        while(index != (nums.size()/2)){
            if(index > nums.size()/2){
                end = index - 1;
                index = partition(nums, start, end);
            }
            else if(index < nums.size()/2){
                start = index + 1;
                index = partition(nums, start, end);
            }
        }
        return nums[nums.size()/2];
    }
};

2. 还有一种是BM投票算法,设置一个计数器,如果计数器为0,则统计当前数的个数,否则如果当前数等于要等于要统计的数则计数器加1,否则减一。

代码如下:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int cnt = 0, num, len = nums.size();
        for(int i =0; i< nums.size(); i++)
        {
            if(cnt == 0) num = nums[i];
            cnt = (num == nums[i])?(cnt+1):(cnt-1);
        }
        return num;
    }
};


你可能感兴趣的:(LeetCode,array,快速排序)