From 5fdcde39faa1eda0c2931f79f6596b532333f109 Mon Sep 17 00:00:00 2001 From: yennanliu Date: Sat, 30 Nov 2024 17:03:06 +0800 Subject: [PATCH] update java-trick cheatsheet --- doc/cheatsheet/java_trick.md | 46 +++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/doc/cheatsheet/java_trick.md b/doc/cheatsheet/java_trick.md index 1a9fc90a..05ce5627 100644 --- a/doc/cheatsheet/java_trick.md +++ b/doc/cheatsheet/java_trick.md @@ -253,7 +253,6 @@ Arrays.sort(x_array); String x_str = new String(x_array); ``` - ### 1-0-5) Access elements in a String ```java // java (via .split("")) @@ -330,6 +329,23 @@ private boolean canForm(String x, String s){ } ``` +### 1-0-7) Access element in StringBuilder + +```java +// java +// LC 767 + +// ... + + StringBuilder sb = new StringBuilder("#"); + + +if (currentChar != sb.charAt(sb.length() - 1)) { + // ... +} +// ... +``` + ### 1-1) Swap elements in char array ```java @@ -1062,3 +1078,31 @@ System.out.println(random.nextInt(10)); System.out.println(random.nextInt(10)); System.out.println(random.nextInt(100)); ``` + + +### 2-9) HashMap - Track element count in order + +```java +// java +// LC 767 + +// ... + +// Step 1: Count the frequency of each character +Map charCountMap = new HashMap<>(); +for (char c : S.toCharArray()) { + charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1); +} + +// Step 2: Use a priority queue (max heap) to keep characters sorted by +// frequency +/** NOTE !!! + * + * we use PQ to track the characters count sorted in order + */ +PriorityQueue> maxHeap = new PriorityQueue<>( + (a, b) -> b.getValue() - a.getValue()); +maxHeap.addAll(charCountMap.entrySet()); + +// ... +``` \ No newline at end of file