leetcode--169. Majority Element

来源:互联网 发布:读懂中国经济数据 上 编辑:程序博客网 时间:2024/04/27 19:40
Question:

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.

思路: 1.  有题目可以知道,所求的元素的数目大于⌊ n/2 ⌋,也就意味着,且该元素是存在的。

    2. 通过每寻找到两个不同的元素的时候,就一块删除掉,剩下最后的就是所求的元素。(因为该元素数目大于⌊ n/2 ⌋该,也就是一半,所以一次                  删除两个不同元素最后就是目标元素

具体代码实现如下:  

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

0 0
原创粉丝点击