[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.

解题说明:

参考:http://www.cnblogs.com/ganganloveu/p/4177690.html

成对删除两个不同的元素,最后剩下的就是Majority elemen.

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int candidate;
 5         int cnt = 0;
 6         int n = nums.size();
 7         
 8         for (int i = 0; i < n; ++i) {
 9             if (cnt == 0) {
10                 candidate = nums[i];
11                 ++cnt;
12             } else {
13                 if (candidate == nums[i]) {
14                     ++cnt;
15                 } else {
16                     --cnt;
17                 }
18             }
19         }
20         
21         return candidate;
22     }
23 };
原文地址:https://www.cnblogs.com/skycore/p/4897298.html