Algorithms Tips (4) – Basic Data Structure

Here we record some basic data structures which are easily involved in coding.

PriorityQueue
Sometimes, we want to sort hashmap by its value, we can introduce PriorityQueue to override its compare function to reach the goal. (Laster, I will add more compare function to popular PriorityQueue’s field.)

For recursion method, we might need to copy the last result to current result. For example, for f(i-1), its result is left (List<Integer>) and for f(i), its result is to merge left with current value.
Wrong version:

The problem of the wrong version is that it will change left’s content. For example, if left=[[], [1]] and nums[1]=2, the wrong version’s output is [[2],[1,2],[2],[1,2]]. For the right version, it creates a new ArrayList to physically build a new list, so later add method won’t change original content. So the right output is [[], [1], [2], [1,2]].

Stack

Stack<String> s = new Stack();
s.push("zara");
s.peek();
s.pop();

String

int integer = 1;
String t = String.valueOf(integer);

The string is very common, so the only special point is to convert to char[] when needed.