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.
我也想到了很多方法,最终用贪心法实现,其实使用map也是挺简单的,有心人可以查一查
1 class Solution { 2 public: 3 int majorityElement(vector<int>& nums) { 4 int len = nums.size(); 5 sort(nums.begin(), nums.end()); 6 if (nums.front() == nums.back()) 7 return nums[0]; 8 9 int count1=0; 10 int count2=0; 11 int num = nums[0]; 12 int num1=0; 13 for (int i = 0; i < len; i++) 14 { 15 16 if (num == nums[i]) 17 { 18 count1++; 19 } 20 else 21 { 22 23 if (count1>count2) 24 { 25 count2 = count1; 26 num1 = num; 27 } 28 num = nums[i]; 29 count1 = 1; 30 } 31 32 } 33 if(count1>count2) 34 return num; 35 else 36 return num1; 37 } 38 };