zoukankan      html  css  js  c++  java
  • 169. Majority Element(LeetCode)

    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.

    我也想到了很多方法,最终用贪心法实现,其实使用map也是挺简单的,有心人可以查一查

     1 class Solution {
     2 public:
     3     int majorityElement(vector<int>& nums) {
     4       int len = nums.size();
     5         sort(nums.begin(), nums.end());
     6          if (nums.front() == nums.back())
     7             return nums[0];
     8             
     9         int count1=0;
    10         int count2=0;
    11         int num = nums[0];
    12         int num1=0;
    13         for (int i = 0; i < len; i++)
    14         {
    15             
    16             if (num == nums[i])
    17             {
    18                 count1++;
    19             }
    20             else
    21             {
    22 
    23                 if (count1>count2)
    24                 {
    25                     count2 = count1;
    26                     num1 = num;
    27                 }
    28                 num = nums[i];
    29                 count1 = 1;
    30             }
    31 
    32         }
    33         if(count1>count2)
    34         return num;
    35         else
    36         return num1;
    37     }
    38 };
  • 相关阅读:
    python中字典一键多相同值反转技巧
    win10下安装mysql
    上台阶问题的具体走法用python来实现
    桥接模式
    适配器模式
    多线程中lock的使用
    原型模式
    多线程
    建造者模式
    代理模式
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6812947.html
Copyright © 2011-2022 走看看