Majority ElementTotal accepted:35645 Total submissions:103047my submissions QuestionSolution
Given an array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋ .
Assume that the array was non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide TagsDivide and conquer Array Bit manipulationHas you met this question in a real interview? Yes No
Discuss
The requirement of this problem is to find the most frequently occurring numbers in the line vectors, and in the title it seems like I want to be able to do it with a divide-and-conquer method, but I use the map to do this, because this record is very fast, the time complexity of map lookup is very small,<int,int> the value stored in first. Second the number of occurrences of the stored value
#include <iostream> #include <vector> #include <map> #include <utility>using namespace Std;int Majorityelement (vector<int>& nums) {map<int,int> temp;int len=nums.size (); int result;if (len==1) { Result=nums[0];return result;} for (int i=0;i<len;i++) {if (Temp.count (Nums[i]) ==0) {Temp.insert (Make_pair (nums[i],1));} else{temp[nums[i]]++;}} Pair<int,int>max_num (Temp.begin ()->first,temp.begin ()->second); for (Map<int,int>::iterator i= Temp.begin (); I!=temp.end (); i++) {if (I->second>max_num.second) {max_num.first=i->first;max_num.second=i- >second;}} Result=max_num.first;return result;} int main () {vector<int> Vec;vec.push_back (2), Vec.push_back (2); Cout<<majorityelement (VEC) <<endl;}
leetcode_169 problem--majority Element (map to use)