LeetCode – Patching Array (Java)

Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required. Example 1: nums = [1, 3], n = 6 Return 1. … Read more

Java Remove Element from ArrayList

To remove some elements from an ArrayList while iterating over the ArrayList, we need to use Iterator. Integer[] arr = {1,2,3,4,5,6}; ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr)); System.out.println(list);   Iterator<Integer> iter = list.iterator(); while(iter.hasNext()){ int i = iter.next(); if(i==5) iter.remove(); }   System.out.println(list);Integer[] arr = {1,2,3,4,5,6}; ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr)); System.out.println(list); Iterator<Integer> iter = list.iterator(); … Read more

LeetCode – Number of Islands II (Java)

A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and … Read more

LeetCode – Find Median from Data Stream (Java)

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. Analysis First of all, it seems that the best time complexity we can get for this problem is O(log(n)) of add() … Read more

LeetCode – Verify Preorder Serialization of a Binary Tree (Java)

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node’s value. If it is a null node, we record using a sentinel value such as #. 9 / \ 3 2 / \ / \ 4 1 # 6 / \ / \ … Read more

Download Large Open Source Java Code Corpus

If you want to dump github repositories or download a large number of open source Java projects, here is the script. There are 2 files required to dump the corpus. The first is “repo-list.txt”. It contains the 39020 Java project names. The second file is “script-zip.sh”. It is the shell script that run git to … Read more

Why do we need generic methods in Java?

1. A Method without Generic Type Assuming you want to write a method that takes two sets and get their intersection. Here is one way to write such a method: public static Set getIntersection(Set set1, Set set2){ Set result = new HashSet();   for(Object o: set1){ if(set2.contains(o)) result.add(o); }   return result; }public static Set … Read more