找出数组中出现次数超过数组长度一半的元素—-腾讯

做法1:利用排序,找出处于排序后的数组处于中间的索引。考虑到时间复杂度的问题,应该优先快排。

做法2:利用 打擂台的方式,相同的元素留下,不同的则删除。

做法3:利用hashMap / hashSet来统计出现的次数

public static int moreThanHalfNum2(int[] nums) {
        if (nums.length == 0)
            return -1;
        int result = nums[0];
        int times = 1;
         //让元素两两打架,相同的留在场上,不同的删掉
        for (int i = 1; i < nums.length; i++) {   
            if (times == 0) {
                result = nums[i];
                times = 1;
            } else if (nums[i] == result)
                times++;
            else
                times--;
        }
        if (!checkMoreThanHalf(nums, result))
            result = -1;
        return result;
    }

扩展:有3个数字出现次数超过1/4。
转载于:http://www.bubuko.com/infodetail-984104.html
#include <iostream>
//上一题的扩展,有3个数字出现次数超过1/4。
using namespace std;
void Grial(int a[], int n)
{
    if (n <= 3)return;
    int count1=0, key1=0;
    int count2=0, key2=0;
    int count3=0, key3=0;
    for (int i = 0; i < n; i++)
    {
        if (!count1 && key2 != a[i] && key3 != a[i])
        {
            count1++;
            key1 = a[i];
        }
        else if (key1 == a[i])
        {
            count1++;
        }
        else  if (key2!=a[i] && key3!=a[i])
        {
            count1--;
        }


        if (!count2 &&key3 != a[i] && key1!=a[i])
        {
            count2++;
            key2 = a[i];
        }
        else if (key2 == a[i])
        {
            count2++;
        }
        else if (key1!=a[i] && key3!=a[i])
        {
            count2--;
        }


        if (!count3 && key1!=a[i] && key2!=a[i])
        {
            count3++;
            key3 = a[i];
        }
        else if (key3 == a[i])
        {
            count3++;
        }
        else if (key1!=a[i] && key2!=a[i])
        {
            count3--;
        }


    }
    cout << key1 << endl;
    cout << key2 << endl;
    cout << key3 << endl;
}
int main()
{
    int a[] = {1,5,5,5,5,2,3,1,2,2,1,1,1,2};
    Grial(a, sizeof(a) / sizeof(int));
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值