题目大意
玩家2心里想一个数N(1≤N≤1,000,000,000),玩家1会进行Q(1≤Q≤50)次询问,每一次询问guessi,玩家2会告诉玩家1:answersi,其中answersi=abs(guessi-N).如果能通过这Q次询问猜出N,则输出N的大小.如果玩家2撒谎了,则输出-2,如果不能猜出N,则输出-1.
题解
涉及的数字为guessi±answersi且数目不会超过Q*2个我们可以用map来存下每一个数被数了几次,如果有有且只有一个数被数了Q次那么这个数就是答案,如果有多个数被数了Q次则输出-1,其他情况输出-2就好了.
代码
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
map<int,int> map1;
class EllysNumberGuessing {
public:
int getNumber(vector<int> guesses, vector<int> answers) {
int n = (int) guesses.size();
int flag = 0, mark = 0;
for (int i = 0; i < n; ++i) {
flag = 0;
if (guesses[i] - answers[i] >= 1) {
map1[guesses[i] - answers[i]]++;
if (map1[guesses[i] - answers[i]] == i + 1) {
flag++;
mark = guesses[i] - answers[i];
}
}
if (guesses[i] + answers[i] <= 1000000000LL) {
map1[guesses[i] + answers[i]]++;
if (map1[guesses[i] + answers[i]] == i + 1) {
flag++;
mark = guesses[i] + answers[i];
}
}
}
if (flag == 1) {
return mark;
}
if (!flag) {
return -2;
}
return -1;
}
};