Leetcode 169 Majority Element (main element) (vector, map)

Source: Internet
Author: User

translation
给定一个长度为n的数组,找出主要的元素。所谓主要的元素是指的出现次数超过? n/2 ?次的元素。你可以假定这个数组是非空的,并且“主要元素”一定是存在的。
Original
anoftheelementelementtheelement that appears more than ? n/2the array is non-emptyandtheelementinthe array.
Analysis

Since test instructions said that the main element is certain, I drilled the loophole, did not intend to ask what n/2 this thing, directly is the longest in all sequences.

1,2,2,3,3,3,3,3,4,4-->1-12-23-54-2

See the key value pair, think of the basic map, there are some complicated containers I use is not very familiar with ...

In this two of the code below, I first defined element elements and then used range-for to facilitate all elements from the nums:

1)如果在map中找不到这个元素,就添加进去;2)如果找到了,将其出现的个数加上1。如果当前的长度大于最大的长度,则进行一些列操作,并将max设置为当前的n,以便于后面的返回。

After debugging, it is found that the nums length is 1, so add a judgment at the beginning.

intMajorityelement ( vector<int>& Nums) {if(nums.size () = =1)returnnums[0]; map<int, int>ElementintMax =0, MaxLen =0; for(AutoN:nums) {if(Element.find (n) = = Element.end ()) {Element.insert ( map<int, int>:: Value_type (N,1)); }Else{Element[n] + =1;if(Element[n] >= maxlen)                {maxlen = Element[n];            max = n; }        }    }returnMax;}
Code
classSolution { Public:intMajorityelement ( vector<int>& Nums) {if(nums.size () = =1)returnnums[0]; map<int, int>ElementintMax =0, MaxLen =0; for(AutoN:nums) {if(Element.find (n) = = Element.end ()) {Element.insert ( map<int, int>:: Value_type (N,1)); }Else{Element[n] + =1;if(Element[n] >= maxlen)                    {maxlen = Element[n];                max = n; }            }        }returnMax }};

Leetcode 169 Majority Element (main element) (vector, map)

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.