zoukankan      html  css  js  c++  java
  • Majority Element

    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.

    思路:

      超过半数的总会剩余

    我的代码:

    public class Solution {
        public int majorityElement(int[] num) {
            if(num == null || num.length == 0)  return -1;
            Stack<Integer> stack = new Stack<Integer>();
            for(int i = 0; i < num.length; i++)
            {
                if(stack.isEmpty()) stack.push(num[i]);
                else
                {
                    int top = stack.peek();
                    if(top == num[i])   stack.push(num[i]);
                    else    stack.pop();
                }
            }
            return stack.pop();
        }
    }
    View Code

    他人代码:

    public class Solution {
        public int majorityElement(int[] num) {
            int maj=0;
            int count = 0;
            int n = num.length;
            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;
        }
    }
    View Code

    学习之处:

    • 思路相似,我的方法空间复杂度O(n) 他人方法O(1) 
    • maj 保存的是到目前扫描为止,发现的最大值,要不要更新最大值看count是否为0

    need to learn

  • 相关阅读:
    [WP]XCTF-Reversing-Newbie_calculations
    [WP]BUUCTF-Reverse-基础题(1-12)
    [WP]XCTF-notsequence
    [WP]XCTF-easyre-153
    [WP]XCTF- 攻防世界-crypto-新手练习区
    [WP]XCTF-simple-check-100
    [WP]XCTF-SignIn
    [WP]XCTF-666
    [WP]XCTF-Reversing-x64Elf-100
    [WP]XCTF-流浪者
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4318565.html
Copyright © 2011-2022 走看看