LeetCode OJ: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.

求大于数组一半的元素,思想主要是对于大于数组一般的元素,给起计数起计数总和一定可以大于其他元素总和,代码如下:

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int count = 0;
 5         int res;
 6         int sz = nums.size();
 7         for(int i = 0; i < sz; ++i){
 8             if(count == 0){
 9                 res = nums[i];
10                 count++;
11             }else{
12                 if(res == nums[i])
13                     count++;
14                 else
15                     count--;
16             }
17         }
18         return res;      
19     }
20 };

 

posted @ 2015-10-29 11:48  eversliver  阅读(306)  评论(0编辑  收藏  举报