mihaibogdan10
BAN USERYou could have added the numbers in the hash as you were doing this, so that you would be able to stop early (e.g. with a target of 10, you can stop after the first two elements if the input is 1 9 4 4 ...)
- mihaibogdan10 October 06, 2013Love the elegance of this piece of code.
- mihaibogdan10 October 05, 2013Not my most elegant piece of code. Would love to hear how you would improve this. Linear in number of elements (BF).
void printLeftmostElements(node *root){
std::queue<node *> queue;
queue.push(root);
int current_level = 1, next_level = 0;
std::cout << root->info << " ";
while(!queue.empty()){
node *current = queue.front();
queue.pop();
if (current->left){
++next_level;
queue.push(current->left);
}
if(current->right){
++next_level;
queue.push(current->right);
}
if (--current_level == 0 && next_level > 0){
std::cout << queue.front()->info << " ";
current_level = next_level;
next_level = 0;
}
}
}
Used the idea presented by @Jay. Expected O(n) time, O(n^2) worst case, and O(n) memory.
#include <iostream>
#include <vector>
#include <unordered_set>
#include <time.h>
#include <cstdlib>
bool addsUp(std::vector<int> input, int target){
std::unordered_set<int> temp_set;
for (int i = 0; i < input.size(); i++){
if (temp_set.find(target - input[i]) != temp_set.end()){
std::cout << "\n" << target - input[i] << " " << input[i];
return true;
}
temp_set.insert(input[i]);
}
return false;
}
int main(){
srand(time(NULL));
std::vector<int> my_vector;
for (int i = 0; i < 10; i++){
my_vector.push_back(rand() % 10);
std::cout << my_vector.back() << " ";
}
std::cout << "\nadds up to 13: " << addsUp(my_vector, 13) << "\n";
}
First, group the anagrams by sorting the letters of each word, and using the word that these sorted letters form as a key for a dictionary.
For example, groups['abc'] = ['abc', 'cab']
Then, take the first word from each of these lists, sort them, then insert the other anagrams accordingly.
- mihaibogdan10 October 10, 2013