実際、あなたの価値は1から100の間であることが非常に重要です!サイズが1,000,000のベクトルでは、等しい数の数字があり、それらのすべてを検査する必要はありません!あなたができることは次のとおりです:
注:次のコードは概要に過ぎません!それは十分なエラーチェックが不足している可能性がありますコピーペーストのためではなく、あなたのアイデアを与えるためだけです!
注2:私が答えを書いたとき、数字は[0、99]の範囲にあると仮定しました。それから私は彼らが実際に[1、100]にいることを読む。明らかに、これは問題ではなく、すべての数字を-1またはそれ以上にすることができ、100から101をすべて101に変更できます。
bool exists[100] = {0}; //exists[i] means whether i exists in your vector
for (unsigned int i = 0, size = vect.size(); i < size; ++i)
exists[vect[i]] = true;
それでは、前と同じようにします:
for(unsigned int x = 0; x < 98; x++)
if (exists[x])
for(unsigned int y = x+1; y < 99; y++)
if (exists[y])
for(unsigned int z = y+1; z < 100; z++)
if (exists[z])
{
//{x, y, z} is an answer
}
あなたができるもう一つのことは、ペアを生成する時間が少なくて済むように準備に時間を費やすことです。例えば:
int nums[100]; //from 0 to count are the numbers you have
int count = 0;
for (unsigned int i = 0, size = vect.size(); i < size; ++i)
{
bool exists = false;
for (int j = 0; j < count; ++j)
if (vect[i] == nums[j])
{
exists = true;
break;
}
if (!exists)
nums[count++] = vect[i];
}
その後、
for(unsigned int x = 0; x < count-2; x++)
for(unsigned int y = x+1; y < count-1; y++)
for(unsigned int z = y+1; z < count; z++)
{
//{nums[x], nums[y], nums[z]} is an answer
}
100を変数と見なしましょう。したがって、 k
とし、配列内の m
( k
)。
最初の方法では、非常に高速な値を検索するために O(n)
準備と O(m ^ 2 * k)
操作があります。
2番目の方法では、値を生成するために O(nm)
準備と O(m ^ 3)
があります。 n
と m
の値を考えると、準備に時間がかかります。
あなたは実際には両方の世界のベストを得るために2つの方法をマージすることができます。
int nums[100]; //from 0 to count are the numbers you have
int count = 0;
bool exists[100] = {0}; //exists[i] means whether i exists in your vector
for (unsigned int i = 0, size = vect.size(); i < size; ++i)
{
if (!exists[vect[i]])
nums[count++] = vect[i];
exists[vect[i]] = true;
}
その後、:
for(unsigned int x = 0; x < count-2; x++)
for(unsigned int y = x+1; y < count-1; y++)
for(unsigned int z = y+1; z < count; z++)
{
//{nums[x], nums[y], nums[z]} is an answer
}
このメソッドは、独自のトリプレットを見つけるために O(n)
準備と O(m ^ 3)
のコストがあります。
Edit: It turned out that for the OP, the same number in different locations are considered different values. If that is really the case, その後、 I'm sorry, there is no faster solution. The reason is that all the possible combinations themselves are C(n, m)
(That's a combination) that although you are generating each one of them in O(1)
, it is still too big for you.