LeetCode | Majority Element
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
解题思路:将容器中的元素排序,遇见相同的数选择计数,如果>n/2了即退出,遇见不同的数对temp值进行更新,继续计数。
实现代码:
class Solution { public: int majorityElement(vector<int>& nums) { int apa=nums.size()/2; sort(nums.begin(),nums.end() ); //对容器里元素进行排序 vector<int>::iterator p=nums.begin(); int temp=*p,cnt=0; for(;p!=nums.end();p++){ if(*p==temp) { cnt++; if(cnt>apa) { return temp; } } if(*p!=temp) { temp=*p; cnt=1; } } } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
posted on 2015-06-08 15:37 Tob__yuhong 阅读(132) 评论(0) 编辑 收藏 举报