besides hash table method, we can also do it like this
The O(n^2) solution is a bit less intuitive - you have to solve the "2SUM" problem in O(n) for a sorted set.
bool ThreeSum(vectornums)
{
std::sort(nums.begin(), nums.end());
for (size_t i = 0; i < nums.size(); i++)
{
size_t j = 0;
size_t k = nums.size() - 1;
while ( j < k )
{
int result = nums[j] + nums[k] - nums[i];
if ( (result < 0) || (i == j) )
j++;
else if ( (result > 0) || (i == k) )
k--;
else
return true;
}
}
return false;
}
No comments:
Post a Comment