这是一个大数据,其中包含1亿个整数,但其中包含一个与其他相同整数不同的值,例如:1,1,1,1 ,1,1,1,42,1,1,1,1 ..但是,我不知道我的下面的代码发生了什么。如何在一串数字中找到一个不同的值
int main() {
vector <int> data;
cout << "Enter same numbers " << " and a different one(negative to be end) :" << endl;
int value;
while (cin >> value && value > 0) {
data.push_back(value);
}
int unique_value;
int size = data.size();
if (data[0] != data[size - 1]) {
if (data[0] != data[2]) {
unique_value = data[0];
} else {
unique_value = data[size - 1];
}
cout << "found the unique number: " << unique_value << endl;
exit(0);
}
int low = 1;
int high = size - 2;
while (high > low) {
if (data[high] != data[low]) {
//其中必有一个是不同的,只要和data[0]就能得到结果
if (data[high] != data[0]) {
unique_value = data[high];
} else {
unique_value = data[low];
}
break;
}
}
if (high == low) {
unique_value = data[high];
}
cout << "found the unique number: " << unique_value << endl;
return 0;
}
BTW,你不需要存储所有号码 - 只是前一个和当前的一个,检查它们在您阅读的 –
你知道这些整数的上限?整数是否被排序? –
你的代码是绝望的错误:即使你正确实现了它,二进制搜索也是行不通的(你没有这样做)。 – dasblinkenlight