Skip to content

Instantly share code, notes, and snippets.

View shixiaoyu's full-sized avatar
🤪
Why so Serious?

Xiaoyu shixiaoyu

🤪
Why so Serious?
View GitHub Profile
public void sortColorsCountingSort(int[] A) {
if (A == null || A.length == 0) return;
int[] buckets = new int[3];
for (int i = 0; i < A.length; i++) {
buckets[A[i]] += 1;
}
int index = 0;
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
int t = n & 1;
n = n >> 1;
res = res << 1;
res = res | t;
}
public TreeNode invertTree(TreeNode root) {
return this.helper(root);
}
// post order
private TreeNode helper(TreeNode root) {
if (root == null) {
return root;
}
public class LRUCacheGoodVersion {
public class Node {
public int val;
public int key;
public Node pre = null;
public Node next = null;
public Node(int k, int v) {
this.key = k;
// I really don't like inheritance, i prefer composition, but the removeEldestEntry is a protected method, have to do this
public class LRULinkedHashMap extends LinkedHashMap<Integer, Integer> {
private int maxSize = -1;
// This is simply use a LinkedHashMap, sort of cheating
public LRULinkedHashMap(int capacity) {
super(16, 0.75f, true); // the 16 hashtable size is not to be confused with the max cache size
this.maxSize = capacity;
}
public int minDistance(String word1, String word2) {
if (word1 == null || word2 == null) return -1;
int l1 = word1.length();
int l2 = word2.length();
if (l1 == 0 || l2 == 0) {
return l1 == 0 ? l2 : l1;
}
public int shortestDistance(String[] words, String word1, String word2) {
if (words == null || words.length == 0 || word1 == null || word2 == null || word1.equals(word2)) {
return -1;
}
int minDistance = words.length;
int wordIndex1 = -1;
int wordIndex2 = -1;
for (int i = 0; i < words.length; i++) {
public int maxSideLength(int[][] mat, int threshold) {
if (mat == null || mat.length == 0 || mat[0].length == 0) {
return 0;
}
int row = mat.length;
int col = mat[0].length;
// easier to implement with the initial value on the boarder to be 0
int[][] prefixSum = new int[row + 1][col + 1];
// the idea of using a prefix sum matrix should be a common technique, each cell contains the sum of
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
int candidate1 = 1;
int candidate2 = 1;
int vote1 = 0;
public String convertSimulationOptimizedImplementation(String s, int nRows) {
if (s == null || s.length() == 0 || nRows <= 0) {
return "";
}
if (nRows == 1) {
return s;
}
int size = s.length();