LeetCode OJ 之 Majority Element (“大部分”元素)

来源:互联网 发布:阿城 作家 知乎 编辑:程序博客网 时间:2024/06/16 07:04

题目:

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.

给定一个n个元素的数组,找出“大部分元”素。“大部分”元素指出现次数超过 n/2 次的元素。

可以假定数组非空,并且存在“大部分”元素。

思路:

每找出两个不同的element,则成对删除。最终剩下的一定就是所求的。即每两个数不一样就抵消掉,一样就记为出现了两次,这样抵消之后的数一定能是出现次数超过n/2次的元素。

代码:

class Solution {public:    int majorityElement(vector<int> &num)     {        int count = 0;        int result = 0;        for(int i = 0 ; i < num.size() ; i++)        {            if(count == 0)            {                result = num[i];                count++;            }            else                if(num[i] != result)                    count--;                else                    count++;                        }        return result;    }};


0 0
原创粉丝点击