leetcode--169. Majority Element

    xiaoxiao2021-03-25  66

    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; } };

    转载请注明原文地址: https://ju.6miu.com/read-38665.html

    最新回复(0)