求字符串里超过字符长度一半的元素

思路

利用栈这种数据结构,可以在时间复杂度为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);
        }
    }


原文地址:https://www.cnblogs.com/dongma/p/13168608.html