zoukankan      html  css  js  c++  java
  • LeetCode | Majority Element

    Majority Element

     Total Accepted: 40685 Total Submissions: 116905My Submissions

    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.

    Show Tags
    Have you met this question in a real interview? 
    Yes
     
    No  
    Discuss


    解题思路:将容器中的元素排序,遇见相同的数选择计数,如果>n/2了即退出,遇见不同的数对temp值进行更新,继续计数。

    实现代码:

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int apa=nums.size()/2;
            sort(nums.begin(),nums.end() );  //对容器里元素进行排序
            vector<int>::iterator p=nums.begin();
            int temp=*p,cnt=0;
            for(;p!=nums.end();p++){
                if(*p==temp)
                {
                    cnt++;
                    if(cnt>apa)
                    {
                         return temp;
                    }
                }
                if(*p!=temp)
                {
                   temp=*p;
                   cnt=1;
                }
            }
        }
    };

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Python--初识函数
    Python中的文件操作
    Python中的集合
    Python中的编码和解码
    Python的关键字is和==
    Python中的字典
    Python中的列表和元组
    Python中几种数据的常用内置方法
    Python的编码
    python_while
  • 原文地址:https://www.cnblogs.com/Tobyuyu/p/4965325.html
Copyright © 2011-2022 走看看