假設您有一個數組值範圍(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;
}
我沒有對驗證部分進行太多的測試,所以可能會出現問題(特別是對於重複的問題)。
我會發布我自己的解決方案作爲答案。
感嘆。這太好了。起初,我嘗試將它作爲for循環來使用,但我不知何故陷入了錯誤的軌道,並以可憎的方式結束。感謝這個答案。 (最後一行應該是missing.add(j),雖然,我認爲) – drby 2009-02-26 12:14:11