Majority Element II leetcode 229

题目大意:找到个数大于总数三分之一的主元素,O(n)时间复杂度,O(1)空间复杂度。

有几种不同的返回情况:

可能没有主元素,可能有一个,可能有两个。

之前的主元素题目一样,要用临时变量来抵消不同的元素,不过不同的是,一个新元素需要抵消两个已有的元素,因为非主元素的个数不会超过总数的1/3,因此最终不会被抵消完。

AC 代码:(C语言)

int* majorityElement(int* nums, int numsSize, int* returnSize) {
    int *res = NULL;
    int n1 = 0, c1 = 0;
    int n2 = 0, c2 = 0;
    int i = 0, t = 0;
    int flag = 0;

    if(1 == numsSize) {
        *returnSize = 1;
        res = (int*)malloc(sizeof(int));
        res[0] = nums[0];
        return res;
    }
    else if(0 == numsSize){
        *returnSize = 0;
        res = (int*)malloc(0);
        return res;
    }

    n1 = nums[0];
    c1 = 1;
    n2 = 0; 
    c2 = 0;
    for (i = 1; i < numsSize; ++i) {
        t = nums[i];
        if (t == n1) ++c1;
        else if (t == n2) ++c2;
        else if (0 == c1) n1 = t, c1 = 1;
        else if (0 == c2) n2 = t, c2 = 1;
        else --c1, --c2;
    }
    c1 = 0;
    c2 = 0;
    *returnSize= 0;
    for (i = numsSize - 1; i >= 0; --i) {
        if (nums[i] == n1) ++c1;
        else if (nums[i] == n2) ++c2;
    }
    if(c1 > numsSize / 3) {
        *returnSize = *returnSize + 1;
        flag |= 1;
    }
    if(c2 > numsSize / 3) {
        *returnSize = *returnSize + 1;
        flag |= 2;
    }
    res = (int*)malloc((*returnSize)*sizeof(int));
    switch(flag) {
        case 0: break;
        case 1: res[0] = n1;break;
        case 2: res[0] = n2;break;
        case 3: res[0] = n1; res[1] = n2;break;
        default: break;
    }
    return res;
}

程序里可以清楚的看到返回的情况。开空间需要用malloc函数: malloc()



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值