我没有测试过这个,也不准备去测试。它的内存占用是O(N),时间复杂度是O(N)。
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
pair<unsigned, unsigned> find_and_sum_pair(vector<unsigned> v)
{
int importantBit = 0;
for(auto num : v)
importantBit = max(importantBit, highest_bit_index(num));
int setEnd;
while((setEnd = partial_sort_for_bit(v, importantBit, v.size())) < 2 && importantBit > 0)
--importantBit;
if(importantBit == 0)
return pair<unsigned, unsigned>();
while(importantBit > 1)
{
unsigned secondSetEnd = partial_sort_for_bit(v, --importantBit, setEnd);
if(secondSetEnd >= 2)
setEnd = secondSetEnd;
}
return pair<unsigned, unsigned>(v[0], v[1]);
}
int partial_sort_for_bit(vector<unsigned> &v, unsigned importantBit, unsigned vSize)
{
unsigned setEnd = 0;
unsigned mask = 1<<(importantBit-1);
for(decltype(v.size()) index = 0; index < vSize; ++index)
if(v[index]&mask > 0)
swap(v[index], v[setEnd++]);
return setEnd;
}
unsigned highest_bit_index(unsigned i)
{
unsigned ret = i != 0;
while(i >>= 1)
++ret;
return ret;
}
我再次遇到了这个问题,并用另一种方法解决了它(对我来说更容易理解):
unsigned findMaxAnd(vector<unsigned> &input) {
vector<unsigned> candidates;
for(unsigned mask = 1<<31; mask; mask >>= 1) {
for(unsigned i : input)
if(i&mask)
candidates.push_back(i);
if (candidates.size() >= 2)
input = move(candidates);
candidates = vector<unsigned>();
}
if(input.size() < 2) {
return 0;
return input[0]&input[1];
}
[3, 4, 6, 7, 8, 9, 17]
。这将产生 8(8 和 9)。 - Kaidul[2 3 8 16 32 64]
,匹配的数字是 2 和 3。 - SomeWittyUsername