169. Majority Element

来源:互联网 发布:地图画路线软件 编辑:程序博客网 时间:2024/06/10 17:26

题目:

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的数组,查找出主元素,就是出现次数大于n/2次的元素。你可以假定数组非空,而且主元素一定存在。


思路:


思路一:因为主元素出现次数大于n/2次,所以可以先将数组排序,取中间n/2处的数即为主元素。

代码:

class Solution {public:    int majorityElement(vector<int>& nums) {                int n = nums.size();        sort(nums.begin(), nums.end());                return nums[n/2];    }};



思路二:主要还是利用的主元素出现次数大于n/2次,维持一个变量count,假定的非主元素count--,假定的主元素count++,最后count值大于0的假定主元素为真的主元素。

代码:

public class Solution {    public int majorityElement(int[] nums) {                int major = nums[0];        int count = 1;                for(int i=1; i<nums.length; i++){            if(count==0){                count++;                major = nums[i];            }else if(major==nums[i]){                count++;            }else{                count--;            }        }          return major;    }}



思路三:利用hash-map的方式实现,当某个元素出现的次数大于n/2次时,结束循环返回主元素。

代码:

class Solution {public:    int majorityElement(vector<int>& nums) {                unordered_map<int, int> mapping;                for(int i=0; i<nums.size(); i++){            if(++mapping[nums[i]] > (nums.size()/2))                return nums[i];        }                return 0;    }};



转载连接:https://leetcode.com/discuss/42929/6-suggested-solutions-in-c-with-explanations

Randomization

This is a really nice idea and works pretty well (16ms running time on the OJ, almost fastest among the C++ solutions). The proof is already given in the suggested solutions.

The code is as follows, randomly pick an element and see if it is the majority one.

class Solution {public:    int majorityElement(vector<int>& nums) {        int n = nums.size();        srand(unsigned(time(NULL)));        while (true) {            int idx = rand() % n;            int candidate = nums[idx];            int counts = 0;             for (int i = 0; i < n; i++)                if (nums[i] == candidate)                    counts++;             if (counts > n / 2) return candidate;        }    }};

Divide and Conquer

This idea is very algorithmic. However, the implementation of it requires some careful thought about the base cases of the recursion. The base case is that when the array has only one element, then it is the majority one. This solution takes 24ms.

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

Moore Voting Algorithm

A brilliant and easy-to-implement algorithm! It also runs very fast, about 20ms.

class Solution {public:    int majorityElement(vector<int>& nums) {        int major, counts = 0, n = nums.size();        for (int i = 0; i < n; i++) {            if (!counts) {                major = nums[i];                counts = 1;            }            else counts += (nums[i] == major) ? 1 : -1;        }        return major;    }};

Bit Manipulation

Another nice idea! The key lies in how to count the number of 1's on a specific bit. Specifically, you need a mask with a 1 on the i-the bit and 0 otherwise to get the i-th bit of each element in nums. The code is as follows.

class Solution {public:    int majorityElement(vector<int>& nums) {        int major = 0, n = nums.size();        for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) {            int bitCounts = 0;            for (int j = 0; j < n; j++) {                if (nums[j] & mask) bitCounts++;                if (bitCounts > n / 2) {                    major |= mask;                    break;                }            }        }         return major;    } };


0 0
原创粉丝点击