169. Majority Element | Java最短代码实现

原题链接: 169. Majority Element

【思路】

用一个c计数,majorEle保存假定的Majority Element,当majorEle与当前数组元素不同的时候,c--,否则c++,当c = 0的时候,用当前数组元素替换majorEle,最后的majorEle一定是Majority Element:

    public int majorityElement(int[] a) {
        int majorEle = a[0], c = 1;
        for (int i = 1; i < a.length; i++) {
            if (majorEle != a[i]) c--;
            else c++;
            if (c == 0) {
                majorEle = a[i];
                c = 1;
            }
        }
        return majorEle;
    }
42 / 42  test cases passed. Runtime: 2 ms  Your runtime beats 60.87% of javasubmissions.


你可能感兴趣的:(169. Majority Element | Java最短代码实现)