Leetcode 169 & 229

Leetcode 169 & 229

169 Majority Element

Description

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.

题意:从一堆元素里面找出出现次数超过⌊ n/2 ⌋ 次的(最多)元素,做法很简单,可以用stl的count或者哈希表求出,也可以用分治法(比较困难),然后有种摩尔投票算法的比较好理解,大致做法就是用一个count初始化为0,然后遇到遍历数组元素第一个元素为1,同时把数组中这个元素赋值给majority,第二个元素与majority比较,相等count++,否则count–,如果count为0就回到上一步继续把下一个元素作为majority,count=1,最后输出majority。放个wiki的链接:Boyer–Moore majority vote algorithm,注意这种算法原型是只能用于找出majority元素(出现次数大于n/2)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count = 0, major, size = nums.size();
        for (int i = 0; i < size; i++) {
            if (count == 0) {
                major = nums[i];
                count += 1;
            } else
                count += major == nums[i]? 1:-1;
        }
        return major;
    }
};

229 Majority Element II

Description

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) {
        int count1 = 0, count2 = 0, size = nums.size(), major1 = -1, major2 = -1;
        vector<int> res;
        for (int i = 0; i < size; i++) {
            if (major1 == nums[i])
                count1++;
            else if (major2 == nums[i])
                count2++;
            else if (count1 == 0) {
                major1 = nums[i];
                count1 = 1;
            } else if (count2 == 0) {
                major2 = nums[i];
                count2 = 1;
            } else {
                count1--;
                count2--;
            }
        }
        count1 = count2 = 0;
        for (int i = 0; i < size; i++) {
            if (major1 == nums[i])
                count1++;
            if (major2 == nums[i])
                count2++;
        }
        if (count1 > size / 3)
            res.push_back(major1);
        if (count2 > size / 3)
            res.push_back(major2);
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值