Skip to content

Instantly share code, notes, and snippets.

View senarukana's full-sized avatar

Zhe Li senarukana

View GitHub Profile
@senarukana
senarukana / triangles.py
Created March 20, 2015 13:55
caluclate the number of triangles
from bisect import bisect_left
def countTriangleTripleIndex(a):
a.sort()
n, count = len(a), 0
for i in range(n-2):
j = i+1
k = bisect_left(a, a[i]+a[j])-1
while k < n:
'''
Given integer array and integer k, return all possible equation that array can be calculated to k.
Operations can be +, -, *, /, ()
1. searchRecursive is the solution that the relative position of array can not be changed
2. search2Recursive is the solution that the relative position can be changed
'''
@senarukana
senarukana / triangle_nums.py
Created May 30, 2015 07:55
num of valid triangles
import bisect
'''
1. sort the array
2. iterate i from 0 to n-3
3. j and k as another two rectangle point, j set to i+1, k set to i+2
4. if a[i] + a[j] >= a[k], move k forward
5. if a[i] + a[j] < a[k], [j+1,...k-1] is legal rectangle,
nums += k-j-1, then move j forward
6. if k equal to n, [i, [j, ..., n-2], n-1] could be rectangle
class InvalidException(Exception):
pass
def encode1(words):
res = ""
for word in words:
res += str(len(word)) + ':' + word
return res
@senarukana
senarukana / utf8.cpp
Last active August 29, 2015 14:22
UTF8 encode
#include <iostream>
using namespace std;
/*
0xxxxxxx A single-byte US-ASCII code (from the first 127 characters)
110xxxxx One more byte follows
1110xxxx Two more bytes follow
11110xxx Three more bytes follow
10xxxxxx A continuation of one of the multi-byte characters
@senarukana
senarukana / construct_pre_bst.py
Created June 2, 2015 14:29
construct bst by preorder
3 1 2 6 4 5
3
1 6
2 4
5
Basic Method:
Use the first element of preorder to divide the problem into 2 sub problems, construct the tree recursively
1. make the first element as root node
@senarukana
senarukana / dot_product.py
Last active November 18, 2017 18:18
dot product sparse vector
# m + n
# element expressed as (pos, value)
def multiply1(vec1, vec2):
i = 0
j = 0
vec = []
while i < len(vec1) and j < len(vec2):
if vec1[i][0] > vec2[j][0]:
@senarukana
senarukana / implement_stack_using_queue.py
Last active October 31, 2015 11:09
stack using queue
from collections import deque
# push O(n)
# top, pop, O(1)
class Stack1:
# initialize your data structure here.
def __init__(self):
self.q = deque()
;; keys define by this won't get override by other module
(defvar my-keys-minor-mode-map (make-keymap) "my-keys-minor-mode keymap.")
;; ident
(global-set-key (kbd ">") 'my-indent-region)
(global-set-key (kbd "<") 'my-unindent-region)
;; remap c-a
(global-set-key [remap move-beginning-of-line]
'smarter-move-beginning-of-line)
;; remap m-d
@senarukana
senarukana / mashal_json.go
Created January 19, 2016 02:58
golang json encode
package marshal
import (
"bytes"
"encoding/json"
"testing"
)
type MarshalInterface interface {
Example() string