Skip to content

Instantly share code, notes, and snippets.

View cli248's full-sized avatar
🎯
Focusing

Chen Liu cli248

🎯
Focusing
View GitHub Profile
@cli248
cli248 / 46.go
Last active August 29, 2015 13:55
A Tour of Go solutions
// #46 Fibonacci closure
package main
import "fmt"
func fibonacci() func() int {
x, y := 0, 1
return func() int {
x, y = y, x+y
@cli248
cli248 / binary_search_first_position.c
Last active August 29, 2015 13:56
Binary search using idea of loop invariant
/*
* Given a sorted array with duplicate elements, find the first index where its element equals to target
* invariant: if key is in A[], then key's index in (low, high), and low + 1 < high
*/
int binary_search_first_position(int *A, int n, int target) {
int low = -1, high = n;
while (low + 1 < high) {
int mid = low + (high - low) / 2;
if (A[mid] < target)
@cli248
cli248 / double_pointer_1.c
Last active December 26, 2015 06:09
Double Pointer Gists: (1) Using double pointer to insert node in a sorted linked list; (2) Using double pointer to remove all elements from a linked list that have value N (3) Using double pointer to remove duplicates from sorted linked list
void insertNode(LinkedList *newIp, LinkedList *list) {
LinkedList **lpp;
LInkedList *lp;
for (lpp = &list; *lpp != NULL; lpp = &(*lpp)->next) {
lp = *lpp;
if (newIp->val < lp->val) {
newIp->next = lp;
*lpp = newIp;
@cli248
cli248 / checkBST.cc
Last active December 26, 2015 11:59
Tree Gists: (1) find the lowest common ancestor of a Binary Tree (2) determine if a Binary Tree is BST or not (3) Inorder Traversal (4) Preorder Traversal (5) Postorder Traversal (6) Inorder without stack or recursive
struct Node {
Node *left;
Node *right;
int _data;
Node(int data) : _data(data), left(NULL), right(NULL) {}
};
bool checkBST(Node *root) {
return help(root, INT_MIN, INT_MAX);
}
@cli248
cli248 / reverse.cpp
Last active December 26, 2015 12:08
Linked List Gists: (1) reverse a linked list
/*
Credit to Leetcode: http://leetcode.com/2010/04/reversing-linked-list-iteratively-and.html
*/
struct Node {
int val;
Node *next;
Node(int value):val(value), next(NULL) {};
};
@cli248
cli248 / subsequence.cc
Last active December 29, 2015 14:49
check if string A is a sub sequence of string B
/*
* Credits: http://stackoverflow.com/questions/8599374/sub-sequence-occurrence-in-a-string
*/
bool checkSubSequence(string A, string B) {
int pos = -1;
bool ok = true;
for (int i=0; i!=A.size() && ok; i++)
ok = (pos = B.find(A[i], pos+1)) != string::npos;
@cli248
cli248 / queue.py
Last active December 31, 2015 04:19
Implement the Queue data structure using two Stacks
class Queue():
def __init__(self):
self.inbox = []
self.outbox = []
def enqueue(self, item):
self.inbox.append(item)
def dequeue(self):
if not self.outbox: