int iNum[5]={n1, n2, n3, n4, n5}; 
想求一个算法:这5个元素,可能有彼此相等的,也有不等的。如何判断,会不会存在3个不相等的情况呢? 
比如1,2,3,1,2这种情况 
当然前提是,并不知道这5个元素分别是什么!
用纯C++写,不用任何库函数实现!

解决方案 »

  1.   

    遍历,判断相等次数是否小于等于3
    int iNum[5]={1, 2, 3, 3, 3};
    int iCount = 0;
    for (int i = 0; i < sizeof(iNum) / sizeof(int); i++)
    {
    for (int j = i + 1; j < sizeof(iNum) / sizeof(int); j++)
    {
    if (iNum[i] == iNum[j])
    {
    iCount++;
    }
    }
    }
      

  2.   

    可能是偶的理解能力有问题,不明白楼主要的最后结果是什么?
    int iNum[5]={n1, n2, n3, n4, n5}; 
    返回值是?Fun(iNum);
      

  3.   

    我对LZ题目的理解是:求5个数中数字的种类数,如果大于等于3就行。
    下面的程序输出yes表示:种数大于等于3#include "iostream"
    using namespace std;
    #include "stdlib.h"#define  N    (5)#define SEE_DETAIL  (1) //set to 0 if U don't want to see so much redundant information.struct Pair{
        int nKey;  //输入的数字的某一个
        int nTimes;//此数字出现次数
    };Pair gArr[N];
    int  gCount = 0; //how many kinds of number currently.//to see if n existing in current array.
    //if existing , return the index , otherwise return -1.
    int FindInArray(int n)
    {
        for (int i=0;i<gCount;i++)
        {
            if (gArr[i].nKey==n)
            {
                return i;
            }
        }//for i
        return -1;
    }int main(int argc, char* argv[])
    {
        int a[N];
        //input the 5 numbers
        cout <<" Input number , one each time"<<endl;
        for (int i=0;i<N;++i)
        {
            cin >> a[i];
        }//for i    //compare with current array,if there are no this kind of number, then insert.
        for (int i=0;i<N;++i)
        {
            int nIndex = FindInArray(a[i]);
            if (nIndex == -1) //not existing,insert
            {
                gArr[gCount].nKey = a[i];
                gArr[gCount].nTimes = 1; //init as 1 times
                ++ gCount; //种类数增加1
            }
            else
            {
                ++ gArr[nIndex].nTimes;
            }
        }//for i    if (gCount >= 3)
        {
            cout <<" yes , there are at least 3 kinds of number "<<endl;
        }
        else 
        {
            cout <<" no , there are at most 2 kinds of number "<<endl;
        }#if SEE_DETAIL 
         for (int i=0;i<N;++i)
         {
             cout << a[i] <<" ";
         }
         cout <<endl;
        for (int i=0;i<gCount;++i)
        {
            cout << "数字 "<< gArr[i].nKey << " , 出现次数 : "<<gArr[i].nTimes << endl;
          
        }//for i
    #endif
        system("PAUSE");
    return 0;
    }
      

  4.   

    楼主这个问题不算什么算法,
    就这个问题来说,如果数据量比较大才比较有价值。
    那种情况下,用Hash 或 Binary Tree 比较有效率。