Majority Element
Total Accepted: 35645 Total Submissions: 103047My Submissions
Question Solution
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Hide Tags
Divide and Conquer Array Bit Manipulation
Have you met this question in a real interview?
Yes
No
这道题的要求是找到行向量中出现次数最多的数字,而在题目中好像希望可以用分治法来做,但是我采用的map来做的,因为这个记录起来很快,map查找的时间复杂度很小,<int,int> first中储存值。second储存值出现的次数
#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; }
时间: 2024-10-28 15:30:55