Majority Element II(leetcode229)

2018-11-30  本文已影响0人  zhouwaiqiang

题目

解题思路

实现代码

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> result = new ArrayList<>();
        //first表示第一个数,second表示第二个数
        //cf表示第一个数出现的次数,cs表示第二个数出现的次数
        int first = 0, second = 0, cf = 0, cs = 0;
        for (int num : nums) {
            if (num == first) cf++;
            else if (num == second) cs++;
            else if (cf == 0) {
                first = num;
                cf++;
            }
            else if (cs == 0) {
                second = num;
                cs++;
            }
            else {
                cf--;
                cs--;
            }
        }
        cf = 0;
        cs = 0;
        for (int num : nums) {
            if (num == first) cf++;
            else if (num == second) cs++;
        }
        if (cf > nums.length / 3) result.add(first);
        if (cs > nums.length / 3) result.add(second);
        return result'
    }
}

参考链接

https://www.cnblogs.com/grandyang/p/4606822.html

上一篇 下一篇

猜你喜欢

热点阅读