xjma1123
BAN USERint distance(vector<string> & dict, string word1, string word2){
if(dict.size() < 2) return -1;
int lastWord1 = -1, lastWord2 = -1;
int minDistance = INT_MAX;
for(int i = 0; i < dict.size(); i++){
if(dict[i] == word1){
lastWord1 = i;
if(lastWord2 != -1){
int distance = i - lastWord2 -1;
minDistance = distance < minDistance? distance:minDistance;
}
}
if(dict[i] == word2){
lastWord2 = i;
if(lastWord1 != -1){
int distance = i - lastWord1 -1;
minDistance = distance < minDistance? distance:minDistance;
}
}
}
return minDistance == INT_MAX? -1: minDistance;
Here is my code with O(n) time and O(1) space.
Node * flip(Node *root){
if(root == NULL) return NULL;
Node *parent, *sibling;
Node *cur = root;
parent = cur->left;
sibling = cur->right;
cur->left = NULL;
cur->right = NULL;
while(parent != NULL){
Node* newParent = parent->left;
Node* newSibling = parent->right;
parent->left = sibling;
parent->right = cur;
cur = parent;
parent = newParent;
sibling = newSibling;
}
return cur;
- xjma1123 September 30, 2014