zoukankan      html  css  js  c++  java
  • 求字符串里超过字符长度一半的元素

    思路

    利用栈这种数据结构,可以在时间复杂度为O(n)内完成,注意这里使用stack是因为
    刚好这个场景下可以使用,有点取巧
     public static void main(String[] args) {
            majorElement(new int[]{4,4,1,2,3,4,4});
        }
        private static void majorElement(int[] arr){
            int[] stack = new int[arr.length];
            int top = -1;
            for (int i : arr) {
                if(top == -1){
                    top++;
                    stack[top] = i;
                }else {
                    int t = stack[top];
                    if(t == i){
                        top++;
                        stack[top] = i;
                    }else {
                        top--;
                    }
                }
            }
            if(top < 0){
                System.out.println("没有超过半数的元素");
            }else {
                System.out.println("major ele:"+stack[top]);
            }
        }

     现在该算法的空间复杂度为O(n),但其实并没有用stack来存放元素的必要

    以为不同元素就会被弹出,相同元素才会进栈,只需要一个记录元素即可,改进后空间复杂度为O(1)

     private static void majorElement(int[] arr){
            int cand = 0;
            int ccount = 0;
            for (int i : arr) {
                if(ccount == 0){
                    cand = i;
                    ccount = 1;
                }else {
                    if(cand == i){
                        ccount++;
                    }else {
                        ccount--;
                    }
                }
            }
            if(ccount < 0){
                System.out.println("没有超过半数的元素");
            }else {
                System.out.println("major ele:"+cand);
            }
        }


  • 相关阅读:
    P4630-[APIO2018]Duathlon铁人两项【圆方树】
    P4980-[模板]Pólya定理
    bzoj4589-Hard Nim【FWT】
    CF700E-Cool Slogans【SAM,线段树合并,dp】
    sqrt数据结构
    NOIP历年好题
    ACM题解吖
    [ZJOI2010]排列计数
    [CQOI2014]数三角形
    [SHOI2007]书柜的尺寸
  • 原文地址:https://www.cnblogs.com/dongma/p/13168608.html
Copyright © 2011-2022 走看看