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

    169. Majority Element(求众数)

    链接:https://leetcode-cn.com/problems/majority-element/

    题目:

      给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

      你可以假设数组是非空的,并且给定的数组总是存在众数。

      示例 1:

      输入: [3,2,3]
      输出: 3
      示例 2:

      输入: [2,2,1,1,1,2,2]
      输出: 2

    思路:

      这题很有趣,多种方法都能解决。我一开始想到的是1.哈希表:数据添加后规模最大的一个就是众数。2.排序:快排或归并排序,中位数就是众数。

      之后看了别人的解法,发现了一种新的方法:摩尔投票算法。摩尔投票法的基本思想很简单,在每一轮投票过程中,从数组中找出一对不同的元素,将其从数组中删除。这样不断的删除直到无法再进行投票,如果数组为空,则没有任何元素出现的次数超过该数组长度的一半。如果只存在一种元素,那么这个元素就是目标元素。

      初始化 count = 1;number = nums[0];之后遍历,如果数字和number相同,count++,不同,count--,count=0时重置number和count,如果众数数量大于n/2,最后的数就是这个。

    代码:

     1 public static int majorityElement(int[] nums) {
     2     int count = 0;
     3     int number = nums[0];
     4     for (int i = 0; i < nums.length; i++) {
     5       if (count == 0) {
     6         number = nums[i];
     7         count = 1;
     8       } else if (number != nums[i]) {
     9         count--;
    10       } else {
    11         count++;
    12       }
    13     }
    14     return number;
    15   }
  • 相关阅读:
    IntelliJ IDEA 14.03 java 中文文本处理中的编码格式设置
    应聘感悟
    STL string分析
    CUDA SDK VolumeRender 分析 (1)
    BSP
    CUDA SDK VolumeRender 分析 (3)
    CUDA SDK VolumeRender 分析 (2)
    Windows软件发布时遇到的一些问题
    Ten Commandments of Egoless Programming (转载)
    复习下光照知识
  • 原文地址:https://www.cnblogs.com/blogxjc/p/11224077.html
Copyright © 2011-2022 走看看