zoukankan      html  css  js  c++  java
  • Majority Element

    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.

    Thoughts:

    This question is a perfect fit for Moore's Voting algorithms. The basic ideas is , 

    1. set a majorityIndex variable to locate the candidate most appeared element.

    2. set a counter to count the occurrences of the majority element (Note: the key point here is to plus one every time the "candidate" majority element appear and minus one every time other element execpet the candidate element appear. The point is that as long as there's a majority element more than 50 percent of the array, we can ensure that the final count is above Zero)

    Solution:

    public class Solution {
        public int majorityElement(int[] nums) {
            if (nums.length == 1) return nums[0];
            int majorIndex = 0;
            int count = 1;
            for(int i = 1 ; i< nums.length; i++) {
                if(nums[i]==nums[majorIndex]) count ++; 
     //compare element with the current candidate majority element
                else count --;
                if(count == 0) {
                    majorIndex = i;// switch candidate
                    count =1 ;
                }
            }
            return nums[majorIndex];
        }
    }
  • 相关阅读:
    LeetCode Notes_#705_设计哈希集合
    LeetCode Notes_#706_设计哈希映射
    【问题记录】用坚果云同步小书匠数据库发生冲突
    Java设计模式5
    Java设计模式4
    Java设计模式3
    Java设计模式2
    Java设计模式1
    tiantian1412/NTU-HsuanTienLin-MachineLearning
    Jing--Li / book
  • 原文地址:https://www.cnblogs.com/midan/p/4644423.html
Copyright © 2011-2022 走看看