leetcode_169 problem--majority Element (map to use)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.