餓了麼2017機試程式設計題
阿新 • • 發佈:2019-02-04
題目描述:
去哪兒網舉辦某活動,每天積極搶單的司機可以獲得額外的收入,因為司機眾多,搶單行為不受控制,因此要防止某些司機作弊,我們把作弊規則定義如下:每天搶單次數比當天所有司機搶單次數和還要多,那麼這個司機就是作弊,那麼問題來了,怎麼用簡單的方法找到作弊的司機。
輸入:
輸入一個不為空的int型陣列,其中每一個int值為司機的ID,表示擁有該ID的司機搶單一次。
輸出:
如果司機存在作弊,則輸出該作弊司機的ID,如果不存在,輸出-1。
樣例輸入:
{1,2,2,4,5,2,7,2,9,2,2}
樣例輸出:
2
題目分析:我考慮方法是自定義一個數組,陣列的每一個元素是一個結構體,該結構體包含了司機的ID和司機的搶單次數,遍歷陣列的時候,如果該ID以前沒有出現過,則新增一個數組節點,如果該ID已經存在,找到該節點,並且把其對應的次數加1,最後便利整個節點陣列,計算出所有搶單的次數和,並且找出次數最多的並且記住此節點的ID,比較這兩個數的差值,如果結果大於等0則不存在作弊的情況輸,出-1即可,如果小於0,則存在作弊的司機,且為次數最多的司機,輸出我們剛才記住的ID即可。
具體的程式碼實現如下:
#include <iostream>
using namespace std;
#define maxsize 100
class Node
{
public:
int ID;
int Times;
};
int main()
{
Node Find[maxsize] = {};
int id, Size = 1, ID = 0;
while (cin >> id)
{
for (int i = 0; i < Size; )
{
if (id != Find[i].ID)
{
if ((i + 1) == Size)
{
Find[i].Times = 1;
Find[i].ID = id;
++Size;
break;
}
}
else if (id == Find[i].ID)
{
Find[i].Times += 1;
break ;
}
i++;
}
}
/*
//顯示Node陣列的資料
for (int j = 0; j < Size - 1; j++)
{
cout << Find[j].ID << "->" << Find[j].Times << endl;
}
*/
int maxtime = 0;
int alltimes = 0, value = 0;
for (int i = 1; i<Size; i++)
{
alltimes += Find[i].Times;
if (maxtime<Find[i].Times)
{
maxtime = Find[i].Times;
ID = i;
}
}
value = alltimes - maxtime;
/*
//顯示測試結果
cout << "maxtime:" << maxtime << endl;
cout << "alltimes:" << alltimes << endl;
cout << "value:" << value << endl;
*/
if (maxtime <= value)
{
cout << "-1" << endl;
}
else if (maxtime>value)
{
cout << ID << endl;
}
system("pause");
return 0;
}