Skip to content

Commit

Permalink
add 767 java
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Nov 30, 2024
1 parent e1caac5 commit 81ae169
Show file tree
Hide file tree
Showing 5 changed files with 352 additions and 11 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1134,7 +1134,7 @@
659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [Python](./leetcode_python/Greedy/split-array-into-consecutive-subsequences.py), [Java](./leetcode_java/src/main/java/LeetCodeJava/Greedy/SplitArrayIntoConsecutiveSubsequences.java) | _O(n)_ | _O(1)_ | Medium | map, pq, greedy, dp, `google`| AGAIN***** (1)
738 | [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) | [Python](./leetcode_python/Greedy/monotone-increasing-digits.py) | _O(1)_ | _O(1)_ | Medium | good trick, greedy, string, trick, `Amazon`| AGAIN********* (4)
763 | [Partition Labels](https://leetcode.com/problems/partition-labels/) | [Python](./leetcode_python/Greedy/partition-labels.py) | _O(n)_ | _O(n)_ | Medium |greedy,trick,dict,index,`amazon`| AGAIN******* (5) (AGAIN)
767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [Python](./leetcode_python/Greedy/reorganize-string.py) | _O(n)_ | _O(1)_ | Medium |`greedy`,`counter`,`good trick`,`amazon`,`fb`| AGAIN**************** (7) (MUST)
767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [Python](./leetcode_python/Greedy/reorganize-string.py), [Java](./leetcode_java/src/main/java/LeetCodeJava/Greedy/ReorganizeString.java) | _O(n)_ | _O(1)_ | Medium |`greedy`,`counter`,`good trick`,`amazon`,`fb`, google| AGAIN**************** (8) (MUST)
861 | [Score After Flipping Matrix](https://leetcode.com/problems/score-after-flipping-matrix/) | [Python](./leetcode_python/Greedy/score-after-flipping-matrix.py) | _O(r * c)_ | _O(1)_ | Medium || AGAIN (not start*)
870 | [Advantage Shuffle](https://leetcode.com/problems/advantage-shuffle/) | [Python](./leetcode_python/Greedy/advantage-shuffle.py) | _O(nlogn)_ | _O(n)_ | Medium || OK*
881 | [Boats to Save People](https://leetcode.com/problems/boats-to-save-people/)|[Python](./leetcode_python/Greedy/boats-to-save-people.py) | _O(nlogn)_ | _O(n)_ | Medium |`good trick`| OK*
Expand Down
2 changes: 1 addition & 1 deletion data/progress.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
20241130: 34
20241130: 34,767
20241126: 722,380
20241125: 33,81
20241124: 153
Expand Down
18 changes: 9 additions & 9 deletions data/to_review.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
2025-01-24 -> ['34']
2025-01-24 -> ['34,767']
2025-01-20 -> ['722,380']
2025-01-19 -> ['33,81']
2025-01-17 -> ['253']
Expand All @@ -8,7 +8,7 @@
2025-01-11 -> ['394']
2025-01-10 -> ['833,950']
2025-01-04 -> ['53,210,207']
2025-01-03 -> ['34', '444']
2025-01-03 -> ['34,767', '444']
2025-01-02 -> ['1188,130,855(again)']
2024-12-30 -> ['722,380']
2024-12-29 -> ['33,81']
Expand All @@ -17,24 +17,24 @@
2024-12-26 -> ['776,31']
2024-12-25 -> ['004(todo),34(todo),162(todo),275(todo)']
2024-12-24 -> ['986(todo),1229(todo),1868(todo),80(todo),209(todo),283(todo),360(todo),713(todo),532(todo),611(todo)']
2024-12-21 -> ['34', '394', '855,846']
2024-12-21 -> ['34,767', '394', '855,846']
2024-12-20 -> ['833,950', '932']
2024-12-18 -> ['951,792']
2024-12-17 -> ['722,380']
2024-12-16 -> ['33,81']
2024-12-14 -> ['253', '53,210,207', '163,1048']
2024-12-13 -> ['34', '776,31', '444', '298,729']
2024-12-13 -> ['34,767', '776,31', '444', '298,729']
2024-12-12 -> ['004(todo),34(todo),162(todo),275(todo)', '1188,130,855(again)', '1146']
2024-12-11 -> ['986(todo),1229(todo),1868(todo),80(todo),209(todo),283(todo),360(todo),713(todo),532(todo),611(todo)']
2024-12-09 -> ['722,380']
2024-12-08 -> ['34', '33,81', '394', '737']
2024-12-08 -> ['34,767', '33,81', '394', '737']
2024-12-07 -> ['833,950', '900', '686,734,737']
2024-12-06 -> ['253', '26,27', '802,1197,26', '353']
2024-12-05 -> ['34', '776,31', '528,334']
2024-12-05 -> ['34,767', '776,31', '528,334']
2024-12-04 -> ['722,380', '004(todo),34(todo),162(todo),275(todo)']
2024-12-03 -> ['34', '33,81', '986(todo),1229(todo),1868(todo),80(todo),209(todo),283(todo),360(todo),713(todo),532(todo),611(todo)', '1145']
2024-12-02 -> ['34']
2024-12-01 -> ['34', '722,380', '253', '53,210,207']
2024-12-03 -> ['34,767', '33,81', '986(todo),1229(todo),1868(todo),80(todo),209(todo),283(todo),360(todo),713(todo),532(todo),611(todo)', '1145']
2024-12-02 -> ['34,767']
2024-12-01 -> ['34,767', '722,380', '253', '53,210,207']
2024-11-30 -> ['33,81', '776,31', '394', '444', '855,846', '1145,1219']
2024-11-29 -> ['722,380', '004(todo),34(todo),162(todo),275(todo)', '833,950', '1188,130,855(again)', '932']
2024-11-28 -> ['722,380', '33,81', '253', '986(todo),1229(todo),1868(todo),80(todo),209(todo),283(todo),360(todo),713(todo),532(todo),611(todo)']
Expand Down
285 changes: 285 additions & 0 deletions leetcode_java/src/main/java/LeetCodeJava/Greedy/ReorganizeString.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,285 @@
package LeetCodeJava.Greedy;

// https://leetcode.com/problems/reorganize-string/description/

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
* 767. Reorganize String
* Solved
* Medium
* Topics
* Companies
* Hint
* Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
*
* Return any possible rearrangement of s or return "" if not possible.
*
*
*
* Example 1:
*
* Input: s = "aab"
* Output: "aba"
* Example 2:
*
* Input: s = "aaab"
* Output: ""
*
*
* Constraints:
*
* 1 <= s.length <= 500
* s consists of lowercase English letters.
*
*
*/
public class ReorganizeString {

// V0
// IDEA : HASHMAP
// TODO : fix below
// public String reorganizeString(String s) {
//
// if (s.length() == 1){
// return s;
// }
//
// ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// for (String x : s.split("")){
// map.put(x, map.getOrDefault(x, 0)+1);
// }
//
// System.out.println(">>> map = " + map);
// StringBuilder sb = new StringBuilder();
// String prev = null;
// //String res = "";
//
// while(!map.isEmpty()){
// for(String k : map.keySet()){
// System.out.println(">>> k = " + k + ", keySet = " + map.keySet() + ", prev = " + prev);
// if (prev != null && prev.equals(k)){
// return "";
// }
// sb.append(k);
// prev = k;
// if (map.get(k) - 1 == 0){
// map.remove(k);
// }else{
// map.put(k, map.get(k)-1);
// }
// }
// }
//
// return sb.toString();
// }

// V1
// IDEA : HASHMAP + PriorityQueue
// https://leetcode.com/problems/reorganize-string/solutions/943268/heap-fetch-2-at-once-with-very-detail-explanations/
public String reorganizeString_1(String S) {

// step 1:
// build a hashmap to store characters and its frequencies:
Map<Character, Integer> freq_map = new HashMap<>();
for (char c : S.toCharArray()) {
freq_map.put(c, freq_map.getOrDefault(c, 0) + 1);
}
// step 2:
// put the char of freq_map into the maxheap with sorting the frequencies by
// large->small
/** NOTE !!!!
*
* make PQ as descending order
*
* (a, b) -> freq_map.get(b) - freq_map.get(a)
*/
PriorityQueue<Character> maxheap = new PriorityQueue<>(
(a, b) -> freq_map.get(b) - freq_map.get(a)
);
// addAll() is adding more then one element to heap
maxheap.addAll(freq_map.keySet());

// now maxheap has the most frequent character on the top

// step 3:
// obtain the character 2 by 2 from the maxheap to put in the result sb
// until there is only one element(character) left in the maxheap
// create a stringbuilder to build the result result
StringBuilder sb = new StringBuilder();
while (maxheap.size() > 1) {
char first = maxheap.poll();
char second = maxheap.poll();
sb.append(first);
sb.append(second);
freq_map.put(first, freq_map.get(first) - 1);
freq_map.put(second, freq_map.get(second) - 1);

// insert the character back to the freq_map if the count in
// hashmap of these two character are still > 0
if (freq_map.get(first) > 0) {
maxheap.offer(first);
}
if (freq_map.get(second) > 0) {
maxheap.offer(second);
}
}

if (!maxheap.isEmpty()) {
// when there is only 1 element left in the maxheap
// check the count, it should not be greater than 1
// otherwise it would be impossible and should return ""
if (freq_map.get(maxheap.peek()) > 1) {
return "";
} else {
sb.append(maxheap.poll());
}
}

return sb.toString();
}

// V2
// https://leetcode.com/problems/reorganize-string/solutions/3948228/100-fast-priorityqueue-with-explanation-c-java-python-c/
public String reorganizeString_2(String s) {
int[] f = new int[26];
int n = s.length();

for (int i = 0; i < n; i++) {
f[s.charAt(i) - 'a']++;
if (f[s.charAt(i) - 'a'] > (n + 1) / 2) {
return "";
}
}

PriorityQueue<Pair> p = new PriorityQueue<>((a, b) -> b.freq - a.freq);
for (int i = 0; i < 26; i++) {
if (f[i] != 0) {
p.offer(new Pair(f[i], (char) (i + 'a')));
}
}

StringBuilder ans = new StringBuilder();
while (p.size() >= 2) {
Pair p1 = p.poll();
Pair p2 = p.poll();
ans.append(p1.ch);
ans.append(p2.ch);
if (p1.freq > 1) {
p.offer(new Pair(p1.freq - 1, p1.ch));
}
if (p2.freq > 1) {
p.offer(new Pair(p2.freq - 1, p2.ch));
}
}

if (!p.isEmpty()) {
ans.append(p.poll().ch);
}

return ans.toString();
}

class Pair {
int freq;
char ch;

Pair(int freq, char ch) {
this.freq = freq;
this.ch = ch;
}
}


// V3
// https://leetcode.com/problems/reorganize-string/solutions/3948110/easy-solution-python3-c-c-java-python-with-image/
public String reorganizeString_3(String s) {
Map<Character, Integer> count = new HashMap<>();
for (char c : s.toCharArray()) {
count.put(c, count.getOrDefault(c, 0) + 1);
}

List<int[]> maxHeap = new ArrayList<>();
for (Map.Entry<Character, Integer> entry : count.entrySet()) {
maxHeap.add(new int[]{-entry.getValue(), entry.getKey()});
}
heapify(maxHeap);

int[] prev = null;
StringBuilder res = new StringBuilder();
while (!maxHeap.isEmpty() || prev != null) {
if (prev != null && maxHeap.isEmpty()) {
return "";
}

int[] top = heapPop(maxHeap);
res.append((char) top[1]);
top[0]++;

if (prev != null) {
heapPush(maxHeap, prev);
prev = null;
}

if (top[0] != 0) {
prev = top;
}
}

return res.toString();
}

private void heapify(List<int[]> heap) {
int n = heap.size();
for (int i = n / 2 - 1; i >= 0; i--) {
heapifyDown(heap, i);
}
}

private void heapifyDown(List<int[]> heap, int index) {
int n = heap.size();
int left = 2 * index + 1;
int right = 2 * index + 2;
int largest = index;

if (left < n && heap.get(left)[0] < heap.get(largest)[0]) {
largest = left;
}
if (right < n && heap.get(right)[0] < heap.get(largest)[0]) {
largest = right;
}

if (largest != index) {
Collections.swap(heap, index, largest);
heapifyDown(heap, largest);
}
}

private int[] heapPop(List<int[]> heap) {
int n = heap.size();
int[] top = heap.get(0);
heap.set(0, heap.get(n - 1));
heap.remove(n - 1);
heapifyDown(heap, 0);
return top;
}

private void heapPush(List<int[]> heap, int[] element) {
heap.add(element);
heapifyUp(heap, heap.size() - 1);
}

private void heapifyUp(List<int[]> heap, int index) {
while (index > 0) {
int parent = (index - 1) / 2;
if (heap.get(index)[0] >= heap.get(parent)[0]) {
break;
}
Collections.swap(heap, index, parent);
index = parent;
}
}

// V3
}
Loading

0 comments on commit 81ae169

Please sign in to comment.