Skip to content

Commit

Permalink
update java-trick cheatsheet
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Nov 30, 2024
1 parent 7ed5538 commit 5fdcde3
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion doc/cheatsheet/java_trick.md
Original file line number Diff line number Diff line change
Expand Up @@ -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(""))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<Character, Integer> 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<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(
(a, b) -> b.getValue() - a.getValue());
maxHeap.addAll(charCountMap.entrySet());

// ...
```

0 comments on commit 5fdcde3

Please sign in to comment.