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)