Majority Element,Majority Element II

一:Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int numsSize = nums.size();
        int times = 0;
        int res = 0;
        for(int i=0;i<nums.size();i++){
            if(i==0){
                res = nums[i];
                times = 1;
            }else{
                if(nums[i]!=res){
                    times--;
                    if(times==0){
                        res = nums[i];
                        times = 1;
                    }
                }else{
                    times++;
                }
            }
        }
        return res;
    }
};

 二: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 ⌋的数,在数组中至多只有两个,可以画图理解。

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> res;
        int numsSize = nums.size();
        int resval1 = 0,resval2=0;
        int times1 = 0,times2=0;
        for(int i=0;i<numsSize;i++){
            if(i==0){
                resval1 = nums[i];
                times1++;
            }else{
                if(nums[i]==resval1){
                    times1++;
                }else if(times2==0){
                    times2=1;
                    resval2 = nums[i];
                }else if(nums[i]==resval2){
                    times2++;
                }else{
                    times1--;
                    times2--;
                    if(times1==0){
                        times1=1;
                        resval1=nums[i];
                    }
                }
            }
        }
        int cnt1=0,cnt2=0;
        for(int i=0;i<numsSize;i++){
            if(nums[i]==resval1)
               cnt1++;
            if(nums[i]==resval2)
               cnt2++;
        }
        if(cnt1>(numsSize/3))
            res.push_back(resval1);
        if(cnt2!=numsSize && cnt2>(numsSize/3))
            res.push_back(resval2);
        return res;
    }
};

 

posted @ 2015-11-12 23:28  zengzy  阅读(174)  评论(0编辑  收藏  举报
levels of contents