leetcode 求众数

https://leetcode-cn.com/problems/majority-element/

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

 

https://leetcode-cn.com/problems/majority-element-ii/

class Solution {
public:
    vector majorityElement(vector& nums) {
        if (nums.size()==0) return {};
        
        int a,b,cnt1=0,cnt2=0;
        for (auto n:nums)
        {
            if (a == n)
                ++cnt1;
            else if (b == n)
                ++cnt2;            
            else if (cnt1 == 0)
            {
                a = n;
                ++cnt1;
            }
            else if (cnt2 == 0)
            {
                b = n;
                ++cnt2;
            }
            else
            {
                --cnt1;
                --cnt2;
            }            
        }       
        
        cnt1 = cnt2 = 0;
        for (auto n:nums)
        {
            if (n == a)            
                ++cnt1;
            else if (n == b)
                ++cnt2;
        }
        
        vector ans;
        if (cnt1>nums.size()/3)
            ans.push_back(a);
        if (cnt2>nums.size()/3)
            ans.push_back(b);        
        return ans;
    }
};

https://leetcode-cn.com/problems/single-number-iii/

class Solution {
public:
    vector singleNumber(vector& nums) {
        int x = 0;
        for (auto n : nums)
            x ^= n;
        
        int bit = 0;
        while(bit < 32)
        {
            if (x & (1< ans;
        x = 0;
        for (int k = 0; k < i; ++k)
        {
            x ^= nums[k];
        }
        ans.push_back(x);
        
        x = 0;
        for (int k = i; k < j; ++k)
        {
            x ^= nums[k];
        }
        ans.push_back(x);
        return ans;
    }
};

 

你可能感兴趣的:(面试算法,leetcode)