leetcode-169. Majority Element

来源:互联网 发布:js异步完成执行函数 编辑:程序博客网 时间:2024/06/07 11:48

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.

思路:当减去两个不同的数后,数组中大于一半的数还是大于一般。这样就把问题不断缩小了

#include<iterator>#include<vector>using namespace std;class Solution {public:    int majorityElement(vector<int>& nums) {        int result = 0;        int count = 0;        vector<int>::iterator iter;        for(iter = nums.begin();iter != nums.end();iter++)        {            if(count == 0)            {                result = *iter;                count++;                continue;            }            if(*iter == result)            {                count++;                continue;            }            count--;        }        return result;    }};
0 0
原创粉丝点击