• LeetCode Majority Element


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

    LeetCode给的这道题的解答真的不错:

    1. Runtime: O(n2) — Brute force solution: Check each element if it is the majority element.
    2. Runtime: O(n), Space: O(n) — Hash table: Maintain a hash table of the counts of each element, then find the most common one.
    3. Runtime: O(n log n) — Sorting: As we know more than half of the array are elements of the same value, we can sort the array and all majority elements will be grouped into one contiguous chunk. Therefore, the middle (n/2th) element must also be the majority element.
    4. Average runtime: O(n), Worst case runtime: Infinity — Randomization: Randomly pick an element and check if it is the majority element. If it is not, do the random pick again until you find the majority element. As the probability to pick the majority element is greater than 1/2, the expected number of attempts is < 2.
    5. Runtime: O(n log n) — Divide and conquer: Divide the array into two halves, then find the majority element A in the first half and the majority element B in the second half. The global majority element must either be A or B. If A == B, then it automatically becomes the global majority element. If not, then both A and B are the candidates for the majority element, and it is suffice to check the count of occurrences for at most two candidates. The runtime complexity, T(n) = T(n/2) + 2n = O(n log n).
    6. Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
      1. If the counter is 0, we set the current candidate to x and the counter to 1.
      2. If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
      After one pass, the current candidate is the majority element. Runtime complexity = O(n).
    7. Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority number’s ith bit must be the one bit that has the greater count.

    public class Solution
    {
    	public int majorityElement(int[] num)
    	{
    		int l=num.length;
    		HashMap<Integer,Integer> data=new HashMap<Integer,Integer>();
    		for (int elem : num) {
                  if (data.containsKey(elem)) {
                      data.put(elem, data.get(elem)+1);
                  }
                  else {
                     data.put(elem, 1);
                 }
             }
    		for(int item:data.keySet())
    		{
    			if(data.get(item)>l/2)
    				return item;
    		}
    		return -1;
    	}
    }
    class Solution {
    public:
        int majorityElement(vector<int> &num) {
        int maj;
        int count = 0;
        int n = int(num.size());
        for (int i = 0; i < n; i++){
            if (count == 0){
                maj = num[i];
                count++;
            }
            else if (num[i] == maj){
                count++;
                if (count > n/2) return maj;
            }
            else count--;
        }
        return maj;
        }
    };



  • 相关阅读:
    c#实现一个打砖块游戏step by step---开篇
    T-SQL语言基础(转载)
    一个经典实例理解继承与多态原理与优点(附源码)---面向对象继承和多态性理解得不够深刻的同学请进
    SQL数据库学习系列之一
    能否优雅解决此编程任务是检验一名开发人员是否已经初具编程思维的分水岭
    C#中的委托和事件(续)
    C# 中的委托和事件(转载)
    任务驱动,学习.NET开发系列第2篇------单词统计
    任务驱动,Winform VS WEB对比式学习.NET开发系列第一篇------身份证解析(不断更新的WEB版本及Winform版本源码)
    Echarts ecomfe 触摸屏 touch 在IE10下无法显示悬浮框
  • 原文地址:https://www.cnblogs.com/frankM/p/4399439.html
Copyright © 2020-2023  润新知