C++求解數組中出現超1/4的三個數字。__C++

來源:互聯網
上載者:User
#include <iostream>using namespace std;//求x!中k因數的個數。int Grial(int x,int k){    int Ret = 0;    while (x)    {        Ret += x / k;        x /= k;    }    return Ret;}int main(){    cout << Grial(10, 2) << endl;    return 0;}//如果要求一個n!中k的因子個數,那麼必定滿足如下的規則。//即x=n/k+n/k^2+n/k^3...(直到n/k^x小於0);#include <iostream>using namespace std;int Grial(int x, int k){    int count = 0;    int n = x;    while (n)    {        n &= (n - 1);        count++;    }    return x - count;}int main(){    cout << Grial(3, 2) << endl;    return 0;}//找出數組中出現次數超過數組一半的數字。#include <iostream>using namespace std;int Grial(int a[], int n){    int count=0;    int key;    for (int i = 0; i < n; i++)    {        if (count == 0)        {            key = a[i];            count = 1;        }        else        {            if (key == a[i])            {                count++;            }            else            {                count--;            }        }    }    return key;}int main(){    int a[] = {1,2,3,4,5,6,3,3,3,3,3};    cout<<Grial(a, sizeof(a) / sizeof(int))<<endl;    return 0;}#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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.