[Leetcode 169, Easy] Majority Element

来源:互联网 发布:双飞燕鼠标怎么样知乎 编辑:程序博客网 时间:2024/06/11 23:38

Problem:

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.

Analysis:

This problem is nothing but an application of map structure. The algorithm can be described as adding 1 to the count, and insert a new count to the map, if the corresponding item does not exist.

Solution:

C++: (1) Hash map

    int majorityElement(vector<int>& nums)    {        int count_size = nums.size() / 2 + 1;        vector<pair<int, int> > element_count(count_size, make_pair(0, 0));        map<int, int> offset;        for(int i = 0 ; i < nums.size(); ++i) {            int position = nums[i] % count_size;            if(element_count[position].second == 0) {                element_count[position].first = nums[i];                element_count[position].second = 1;                offset[nums[i]] = position;            } else if(element_count[position].first == nums[i]) {                ++element_count[position].second;            } else {                if(offset.find(nums[i]) != offset.end()) {                    ++element_count[offset[nums[i]]].second;                } else {                    for(int j = 1; j < count_size; ++j) {                        position = (nums[i] + j)% count_size;                        if(element_count[position].second == 0) {                            element_count[position].first = nums[i];                            element_count[position].second = 1;                            offset[nums[i]] = position;                            break;                        }                    }                }            }        }                for(int i = 0; i < element_count.size(); ++i) {            if(element_count[i].second >= count_size)                rv = element_count[i].first;        }                return rv;    }
(2) Bit manipulations:

    int majorityElement(vector<int>& nums)     {        int result = 0;        for (int i=0; i<32; i++) {            int count = 0;            for (int j=0; j<nums.size(); j++) {                if((nums[j]>>i&1) ==1) {                    count++;                }            }            if (count > nums.size() / 2) {                result |= (1<<i);            }        }        return result;    }

(3) Moore Voting Algorithm

    int majorityElement(vector<int>& nums)     {        int elem = 0;        int count = 0;                for (int i=0; i<num.length; i++) {            if (count == 0) {                elem = num[i];                count = 1;            } else {                if (elem == num[i]) {                    count++;                } else {                    count--;                }            }        }        return elem;    }
Java:


Python:



0 0
原创粉丝点击