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

来源:互联网 发布:深圳网络出租屋新规 编辑:程序博客网 时间:2024/06/05 18:13

做法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