Skip to content

Commit 5fdcde3

Browse files
committed
update java-trick cheatsheet
1 parent 7ed5538 commit 5fdcde3

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

doc/cheatsheet/java_trick.md

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,6 @@ Arrays.sort(x_array);
253253
String x_str = new String(x_array);
254254
```
255255

256-
257256
### 1-0-5) Access elements in a String
258257
```java
259258
// java (via .split(""))
@@ -330,6 +329,23 @@ private boolean canForm(String x, String s){
330329
}
331330
```
332331

332+
### 1-0-7) Access element in StringBuilder
333+
334+
```java
335+
// java
336+
// LC 767
337+
338+
// ...
339+
340+
StringBuilder sb = new StringBuilder("#");
341+
342+
343+
if (currentChar != sb.charAt(sb.length() - 1)) {
344+
// ...
345+
}
346+
// ...
347+
```
348+
333349
### 1-1) Swap elements in char array
334350

335351
```java
@@ -1062,3 +1078,31 @@ System.out.println(random.nextInt(10));
10621078
System.out.println(random.nextInt(10));
10631079
System.out.println(random.nextInt(100));
10641080
```
1081+
1082+
1083+
### 2-9) HashMap - Track element count in order
1084+
1085+
```java
1086+
// java
1087+
// LC 767
1088+
1089+
// ...
1090+
1091+
// Step 1: Count the frequency of each character
1092+
Map<Character, Integer> charCountMap = new HashMap<>();
1093+
for (char c : S.toCharArray()) {
1094+
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
1095+
}
1096+
1097+
// Step 2: Use a priority queue (max heap) to keep characters sorted by
1098+
// frequency
1099+
/** NOTE !!!
1100+
*
1101+
* we use PQ to track the characters count sorted in order
1102+
*/
1103+
PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(
1104+
(a, b) -> b.getValue() - a.getValue());
1105+
maxHeap.addAll(charCountMap.entrySet());
1106+
1107+
// ...
1108+
```

0 commit comments

Comments
 (0)