Majority Element II

原题:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

解题:
这个其实跟编程之美上面的“寻找发帖水王”的题如出一辙,也就是寻找一个数组中超过一半的元素。只不过此题把超过一半的元素改成了超过n/3的元素,那么这时只需要采用同样的思路即可。也就是数组只有不超过两个元素满足这样的条件,遍历一遍数组既可以找出这两个元素,然后再遍历两边数组统计这两个元素出现的次数是否满足大于n/3的要求即可。可以AC的C++代码如下(O(N), O(1)):

 vector<int> majorityElement(vector<int>& nums) {
        vector<int> ret;
        int size = nums.size();
        if(size < 0){
            return ret;
        }

        int first = 0, second = 0;
        int index1 = 0, index2 = 0;

        for(int i=0; i<size; i++){
            if(index1 == 0 || first == nums[i]){
                index1 ++;
                first = nums[i];
            }else if(index2 == 0 || second == nums[i]){
                index2 ++;
                second = nums[i];
            }else{
                index1 --;
                index2 --;
            }
        }
        index1 = index2 = 0;
        for(int i=0; i<size; i++){
            if(nums[i] == first)
               index1 ++;
            else if(nums[i] == second)
               index2 ++;
        }

        if(index1 > (size / 3))
            ret.push_back(first);
        if(index2 > (size / 3))
            ret.push_back(second);

        return ret;
    }

你可能感兴趣的:(LeetCode,C++,算法,编程之美)