169. Majority Element c语言

1、来源:点击打开链接

2、题目:

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.

3、暴力破解,又超时,宝宝 心里苦啊

int majorityElement(int* nums, int numsSize) {
    int i,j,f,k=0;
    int *a=(int*)malloc(sizeof(int)*numsSize);
    for(i=0;i<numsSize;i++)
        a[i]=0;
    for(i=0;i<numsSize;i++){
        if(i==0){
            a[0]++;
        }
        else{
            f=0;
            for(j=0;j<i;j++){
                if(nums[j]==nums[i]){
                    f=1;
                    break;
                }
            }
            if(f==0){
                a[i]++;
            }
            else
                a[j]++;
        }
    }
    for(i=0;i<numsSize;i++){
        if(a[i]>numsSize/2){
            break;
        }
    }
    return nums[i];
}
4、参考: 点击打开链接

int majorityElement(int* nums, int numsSize) {
    int i,count=1,major=nums[0];
    for(i=1;i<numsSize;i++){
        if(count==0){
            count++;
            major=nums[i];
        }
        else if(major==nums[i]) count++;
        else count--;
    }
    printf("%d\n",major);
    return major;
}

Great idea!
And I want to express my thinking of this solution.

When count != 0 , it means nums[1...i] has a majority,which is major in the solution.
When count == 0 , it means nums[1...i ] doesn't have a majority, so nums[1...i ] will not help nums[1...n].And then we have a subproblem of nums[i+1...n].

I think it's kind of DP.

5、另一种思路,排序之后中间那个元素就是出现最多的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值