Refactor and speed up a slow but correct C++ function.
Unlock detailed company stats for this questionUpgrade
The task as given (the current implementation is correct but slow):
// Refactor and speed up the code below // The current implementation is correct but slow
int root_node(std::vector<int> output) { int leaf = std::numeric_limits<int>::max(); // Initialize to minimum value
int x = 0, counter = 1; for (size_t node = 0; node < output.size(); ++node) { int edge = output[node]; auto begin = output.begin(); std::advance(begin, node); auto it = std::find_if(begin, output.end(), [edge](int node) { return edge == node; }); x = std::abs(edge); for (size_t j=0, j!= Std::end(output) && j<output.size()-node ,++j)
{ int vertex =output[(j+node)%output.size()];
constexpr auto digits = std::numeric_limits<int>::digits; int direction = ((unsigned int)(vertex - edge)) >> digits; int distance = (1 - direction) * std::pow(edge - vertex, 2); if (leaf == std::numeric_limits<int>::max()) { leaf = std::min(leaf, distance); } else if (distance == std::numeric_limits<int>::max()) { leaf = std::min(leaf, distance); } else { leaf = std::max(leaf, distance); // should this be min? } } } int j = [&](int old_value) { if (counter > x) { leaf = std::min(leaf, old_value); return old_value; } return leaf; }(leaf); for (int ff = 0; ff < leaf; ++ff) { if (ff * ff == leaf) { return ff; } } return leaf;
}
Format · Online assessment.
Community answers
No answers contributed by the community yet.
Related courses

Course

Course
Course
