LeetCode 169 Majority Element (main Element) (vector, map)
Translation
Give an array with the length of n to find the main element. The so-called main element means that the number of occurrences exceeds? N/2? . You can assume that the array is non-empty and the "main element" must exist.
Original
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.
Analysis
Since the meaning of the question says that this main element must exist, I drilled down the gap and did not intend to find the n/2, which is directly the longest of all sequences.
1,2,2,3,3,3,3,3,4,4-->1-12-23-54-2
When I saw a key-Value Pair and thought of a basic map, I was not familiar with some complicated containers ......
In the following code, I first defined the element and used range-for to facilitate all the elements from nums:
1) if this element cannot be found in the map, add it. 2) If yes, add 1 to the number. If the current length is greater than the maximum length, perform some column operations and Set max to the current n to facilitate subsequent return.
After debugging, it is found that the nums length is 1, so a judgment is added at the beginning.
int majorityElement(vector
& nums) { if (nums.size() == 1) return nums[0]; map
element; int max = 0, maxLen = 0; for (auto n : nums) { if (element.find(n) == element.end()) { element.insert(map
::value_type(n, 1)); } else { element[n] += 1; if (element[n] >= maxLen) { maxLen = element[n]; max = n; } } } return max;}
Code
class Solution {public: int majorityElement(vector
& nums) { if (nums.size() == 1) return nums[0]; map
element; int max = 0, maxLen = 0; for (auto n : nums) { if (element.find(n) == element.end()) { element.insert(map
::value_type(n, 1)); } else { element[n] += 1; if (element[n] >= maxLen) { maxLen = element[n]; max = n; } } } return max; }};