Skip to content

Instantly share code, notes, and snippets.

class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
if not matrix or len(matrix) == 0:
return False
# Flatten the matrix into 1D array, complexity is O(K).
# K means the length of the new array.
@rioshen
rioshen / convert_sorted_array_bst.py
Created May 2, 2014 20:15
[leetcode] Convert Sorted Array to Binary Search Tree
#!/usr/bin/env python
__author__ = 'Rio'
class TreeNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
@rioshen
rioshen / erpn.py
Last active August 29, 2015 14:00
Evaluate Reverse Polish Notation
class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
"""Calculates tokens and returns the result.
Use stack to store numbers and pop two numbers once
meets operators then push the calculated result back.
"""
OPS = {
@rioshen
rioshen / codingbat.py
Last active August 29, 2015 14:01
CodingBat.com, python solutions.
#!/usr/bin/env python
__author__ = 'Rio'
def sleep_in(weekday, vacation):
return True if not weekday or vacation else False
def monkey_trouble(a_smile, b_smile):
@rioshen
rioshen / CodingBat.java
Last active August 29, 2015 14:01
CodingBat.com, java solutions.
/**
* The parameter weekday is true if it is a weekday, and the parameter vacation
* is true if we are on vacation. We sleep in if it is not a weekday or we're
* on vacation. Return true if we sleep in.
*/
public boolean sleepIn(boolean weekday, boolean vacation) {
return !weekday || vacation;
}
/**
@rioshen
rioshen / RotateMatrix.java
Created June 8, 2014 20:11
Rotate a matrix
/**
* Rotate a matrix clockwise.
*/
public class RotateMatrix {
/**
* Solution:
* We can use standard Matrix Rotation algorithm.
*/
public static int[][] rotateClockwise(int[][] matrix) {
final int M = matrix.length;
@rioshen
rioshen / Compression.java
Created June 8, 2014 23:12
Run-length string compression
/**
* Compress data
*/
public class Compressoin{
/**
* Solution:
* 1. Insert the picked character from source into the destination string
* 2. Count the number of subsequent occurences and append it to the destination.
* 3. Pick the next character and repeat.
@rioshen
rioshen / ReplaceWhitespace.java
Created June 8, 2014 23:22
URL encoding problem - replace all <space> with %20
/**
* Replace whitespace with %20 in a string.
*/
public class ReplaceWhitespace{
/**
* Solution: Use string built-in method - replaceAll
* Time Complexity: O(N), where N means the length of string
*/
public static String replaceSpaces(String str) {