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

    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】java HashMap

    我们用java的HashMap,把数组中的值做为键,把元素的数目作为值。如果出现了一个元素的数目大于nums.length/2,则返回该值。代码如下:

     1 public class Solution {
     2     public int majorityElement(int[] nums) {
     3         if(nums.length==0 || nums==null) return 0;
     4         Map<Integer, Integer> map = new HashMap<>();
     5         
     6         for(int i = 0; i < nums.length; i++){
     7             if(map.containsKey(nums[i])){
     8                 if(map.get(nums[i])+1 > nums.length/2) return nums[i];
     9                 map.put(nums[i], map.get(nums[i])+1);
    10             }
    11             else
    12                 map.put(nums[i], 1);
    13         }
    14         return nums[0];
    15     }
    16 }

    【思路2】

    由于数组中肯定存在一个majority number。因此我们可以遍历数组,如果找到一对值不同的元素就把他们删除,那么最后剩下的一定majority number。这种算法叫Moore’s Voting Algorithm,由Robert S.Boyer 和J Strother Moore于1980年发明,是线性时间复杂度。

    举个例子:[1,2,3,1,1,1] (1,2)是一对不相同的元素,(3,1)是另一对不相同的元素,那么剩下的1肯定是majority number。代码如下:

     1 public class Solution {
     2     public int majorityElement(int[] nums) {
     3         if(nums.length==0 || nums==null) return 0;
     4         int count = 0;
     5         int result = 0;
     6         
     7         for(int i = 0; i < nums.length; i++){
     8             if(count == 0){
     9                 result = nums[i];
    10                 count = 1;
    11             }
    12             else{
    13                 if(nums[i] == result){
    14                     count ++;
    15                 }
    16                 else count --;
    17             }
    18         }
    19         return result;
    20     }
    21 }

    当然,这种算法对于存在主元素的数组是有效的,如: A A A C C B B C C C B C C

    它肯定能返回主元素C。但是,如果不存在主元素,那么得到的结果就跟遍历顺序有关了。如: A A A C C C B

    如果是从左到右,那么结果是B,如果是从右到左,那么结果是A。

  • 相关阅读:
    深度学习训练模型时保存Log输出信息为文件
    Docker 测试场景领域应用剖析
    kafka性能测试
    [标点符] 初学机器学习算法之LightGBM (直方图+单边梯度采样优化+互斥特征绑定优化)
    【12月DW打卡】joyful-pandas
    【12月DW打卡】joyful-pandas
    【12月DW打卡】joyful-pandas
    【12月DW打卡】joyful-pandas
    【12月DW打卡】joyful-pandas
    Linux安装Redis
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5516395.html
Copyright © 2011-2022 走看看