Java Notes - notruilin/LeetCode GitHub Wiki

Basic

  1. Integer range: -2,147,483,648 to 2,147,483,647 (-2^31 to 2^31 - 1)
  2. String only contains digitals: str.matches("[0-9+]")
  3. Char is digital: Character.isDigit(chr)

Array

  1. Initialise an array with values: String[] arr = {"One", "Two", "Three"};

  2. Sort an array: Arrays.sort(arr);

  3. Sort with lambda:

    Arrays.sort(arr, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]))

  4. Array to ArrayList: List lst = Arrays.asList(arr);

ArrayList

  1. Initialise an ArrayList with values: List<String> lst = Arrays.asList("xyz", "abc");
  2. Sort an ArrayList: Collections.sort(list);

Queue

Queue<Integer> queue = new LinkedList();
queue.isEmpty() -> boolean
queue.add(1);
queue.poll()  // Retrieves and removes the head of this queue, or returns null if empty
queue.peek()  // Retrieves but does not removes the head of this queue, or returns null if empty
queue.contains(1) -> boolean

Stack

Stack<Integer> stack = new Stack();
stack.push(1)
stack.empty()
stack.peek()
stack.pop()

HashSet

HashSet<Integer> set = new HashSet();
set.add(1);
set.clear();  // Removes all of the elements from this set
set.contains(1) -> boolean
set.isEmpty()
set.remove(1) -> boolean
for (String s : set) {
    System.out.println(s);
}

HashMap

HashMap<Character, Integer> map = new HashMap();
map.put(c, num);
map.get(c)
map.containsKey()
map.keySet()

PriorityQueue

PriorityQueue<String> queue = new PriorityQueue(); 
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((x, y) -> Integer.compare(y, x));  // Max heap
queue.add("abc");
queue.clear();
queue.peek();
queue.poll();
queue.remove("abc");

TreeSet

TreeSet<Integer> tree = new TreeSet();
tree.add(1);
tree.contains(1)
tree.isEmpty()
tree.remove()
tree.pollFirst()
tree.pollLast()
tree.higher(1)  // Returns the least element in this set **strictly greater than** the given element, or null if there is no such element.
tree.ceiling(1)  // Returns the least element in this set **greater than or equal to** the given element, or null if there is no such element.
tree.lower(1)  // Returns the greatest element in this set **strictly less than** the given element, or null if there is no such element.
tree.floor(1)  // Returns the greatest element in this set **less than or equal to** the given element, or null if there is no such element.
tree.first()  // Returns the first (lowest) element currently in this set.
tree.last()  // Returns the last (highest) element currently in this set.

TreeMap

TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "val");
map.containsKey(3)
map.get(3)
map.remove(3)
map.replace(3, "newVal")
map.pollFirstEntry().getKey()
map.pollLastEntry().getValue()
map.higherEntry()
map.ceilingEntry()
map.lowerEntry()
map.floorEntry()
map.firstKey()
map.firstEntry()
map.lastKey()
map.lastEntry()
⚠️ **GitHub.com Fallback** ⚠️