假设您在数组中有一个排序范围(x 到 y)的值。
x = 3;
y = 11;
array == 3, 4, 5, 6, 7, 8, 9, 10, 11
但有可能有些值是重复的,有些是缺失的,所以你可能有:
array == 4, 5, 5, 5, 7, 8, 9, 10, 10
用您的语言查找所有重复值和缺失值的最佳方法是什么,以便您获得:
resultMissingValuesArray == 3, 6, 11
resultDuplicatesArray == 5, 5, 10
这里有一些 C++ 代码可以帮助您入门:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
const int kLastNumber = 50000; // last number expected in array
const int kFirstNumber = 3; // first number expected in array
int main()
{
vector<int> myVector;
// fill up vector, skip values at the beginning and end to check edge cases
for(int x = kFirstNumber + 5; x < kLastNumber - 5; x++)
{
if(x % 12 != 0 && x % 13 != 0 && x % 17 != 0)
myVector.push_back(x); // skip some values
else if(x % 9 == 0)
{
myVector.push_back(x); // add duplicates
myVector.push_back(x);
}
else if(x % 16 == 0)
{
myVector.push_back(x); // add multiple duplicates
myVector.push_back(x);
myVector.push_back(x);
myVector.push_back(x);
}
}
// put the results in here
vector<int> missingValues;
vector<int> duplicates;
// YOUR CODE GOES HERE
// validate missingValues for false positives
for(int x = 0; x < (int) missingValues.size(); ++x)
{
if(binary_search(myVector.begin(), myVector.end(), missingValues.at(x)))
cout << "Oh noes! You missed an unmissed value. Something went horribly, horribly wrong.";
}
// validate duplicates (I think... errr)
vector<int>::iterator vecItr = myVector.begin();
vector<int>::iterator dupItr = duplicates.begin();
while(dupItr < duplicates.end())
{
vecItr = adjacent_find(vecItr, myVector.end());
if(*vecItr != *dupItr)
cout << "Oh noes! Something went horribly, horribly wrong.";
// oh god
while(++dupItr != duplicates.end() && *(--dupItr) == *(++dupItr) && *vecItr == *(++vecItr));
++vecItr;
}
return 0;
}
我没有对验证部分进行太多测试,所以它们可能有问题(尤其是重复的部分)。
我将发布我自己的解决方案作为答案。