Skip to content

Instantly share code, notes, and snippets.

View senarukana's full-sized avatar

Zhe Li senarukana

View GitHub Profile
@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
'''
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 / 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:
@senarukana
senarukana / remove_continuous.cpp
Created March 14, 2015 15:48
消除连续的字符串
#include <iostream>
using namespace std;
void removeContinuous(string &s) {
int n = s.size();
int i = 1, j = 0;
while (i < n) {
if (s[i] != s[j]) {
s[++j] = s[i];
@senarukana
senarukana / random_selection.py
Last active August 29, 2015 14:17
随机数相关
# -*- coding: utf-8 -*-
import random
import sys
def random_select(a):
ret = a[0]
for i in range(1, len(a)):
j = random.randint(0, i)
if j == i:
@senarukana
senarukana / shortest_path.py
Last active August 29, 2015 14:17
最短路径
import heapq
class Vertex:
def __init__(self, val):
self.val = val
self.adjs = {}
def add_edge(self, j, val):
self.adjs[j] = val
@senarukana
senarukana / longest_repeating_substring.py
Created March 13, 2015 07:00
出现多于一次的最长的子串
ALPHABETSIZE = 26
def get_index(c):
return ord(c)-ord('a')
class PostfixTreeNode:
@senarukana
senarukana / postfix_tree.py
Created March 13, 2015 06:46
字符串中重复次数最多的子串
ALPHABETSIZE = 26
def get_index(c):
return ord(c)-ord('a')
class PostfixNode:
def __init__(self):
@senarukana
senarukana / multi_postorder.py
Created March 13, 2015 03:16
判断两颗多叉树关于叶子节点的前序遍历是否相等
class TreeNode:
def __init__(self, val):
self.children, self.val = [], val
class PostorderIterator:
def __init__(self, root):
self.st = []
@senarukana
senarukana / young_matrix.py
Created March 11, 2015 07:58
young matrix
ef add(self, val):
if self.size >= self.m * self.n:
return False
i, j = self.m-1, self.n-1
self.mat[i][j] = val
while True:
ni, nj = i, j
if i > 0 and self.mat[i-1][j] > self.mat[ni][nj]:
ni, nj = i-1, j
if j > 0 and self.mat[i][j-1] > self.mat[ni][nj]: