算法设计Week2 LeetCode #169 Majority Element

来源:互联网 发布:依然范特西 知乎 编辑:程序博客网 时间:2024/04/30 22:35

题目描述:

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.

解法一:

使用一个hash表来存储数组中每个元素出现的次数,如果出现次数大于 ⌊ n/2 ⌋ 的元素,直接返回这个元素。

class Solution {public:    int majorityElement(vector<int>& nums) {        unordered_map<int, int> hash_map;        for(int i = 0; i < nums.size(); i++){            if(hash_map.find(nums[i]) != hash_map.end()){                hash_map[nums[i]]++;            }else{                hash_map[nums[i]] = 1;            }            if( hash_map[nums[i]] > nums.size() / 2 )                return nums[i];        }        return 0;    }};
0 0
原创粉丝点击