Posts

Showing posts from December, 2017

Union Find algorithm for disjoint set (并查集算法)

Mainly need to implement two functions `Union` and `Find`, then it is pretty straight forward to use these two functions to get the number of clusters or find the redundant edges etc.  (1)     684   Redundant Connection       class Solution { public:     vector<int> parent;     vector<int> rank;     int Find(int x) {         if (x != parent[x])             // return Find(parent[x]); // Non optimized version             parent[x] = Find(parent[x]); // Optimized version. Flatten the tree while finding               // Please note you cannot just return x instead, assuming x is always equal to parent[x].         // It is possible that x == parent[x] in the first recursion. But the recursion call return         // value will update the global va...

Linked List Summary

(1) How to judge whether there is a loop inside a linked list?  Use quick and slow pointer. (2) How to delete a node in a single linked list? Given node Copy the next node to overwrite the given one. Reference: http://blog.csdn.net/fanoluo/article/details/49478079 Delete:  237  Delete Node in a Linked List         ListNode* next = node->next;         // assert(next)         node->val = next->val;         node->next = next->next; Reverse: (1).   206  Reverse Linked List      (a) Recursive       Base cases: if (!head || !head->next) return head;        Recursive formula:  recursive on the next element and get the newHead:        ListNode *newHead = reverseList(head->next); Find the tail...

Array Summary

Array 1.  Two Sum      Hash table (map<int, int> hashMap; // first is the value, second is the index),f                          find(target - numbers[i]); 167   Two Sum II - Input array is sorted    // Utilize the fact that the array is sorted, sum from both left and right side. // If the summation is too large, decrease the high index, else if the summation // is too low, increase the low index. else if the summation is the target value, // create the vector<int> and return the vector<int>({low + 1, hight + 1}) 170. Two Sum III - Data structure design          Solution:  Two Sum III