File tree Expand file tree Collapse file tree 2 files changed +82
-0
lines changed
Expand file tree Collapse file tree 2 files changed +82
-0
lines changed Original file line number Diff line number Diff line change @@ -659,6 +659,43 @@ Collections.sort(collected, new Comparator<String>() {
659659});
660660```
661661
662+ ### 1-4-5) Sort on ` Hash Map's key and value ` **** *
663+
664+
665+ ``` java
666+ // LC 692
667+
668+
669+ // IDEA: map sorting
670+ HashMap<String , Integer > freq = new HashMap<> ();
671+ for (int i = 0 ; i < words. length; i++ ) {
672+ freq. put(words[i], freq. getOrDefault(words[i], 0 ) + 1 );
673+ }
674+ List<String > res = new ArrayList (freq. keySet());
675+
676+ /**
677+ * NOTE !!!
678+ *
679+ * we directly sort over map's keySet
680+ * (with the data val, key that read from map)
681+ *
682+ *
683+ * example:
684+ *
685+ * Collections.sort(res,
686+ * (w1, w2) -> freq.get(w1).equals(freq.get(w2)) ? w1.compareTo(w2) : freq.get(w2) - freq.get(w1));
687+ */
688+ Collections . sort(res, (x, y) - > {
689+ int valDiff = freq. get(y) - freq. get(x); // sort on `value` bigger number first (decreasing order)
690+ if (valDiff == 0 ){
691+ // Sort on `key ` with `lexicographically` order (increasing order)
692+ // return y.length() - x.length(); // ?
693+ return x. compareTo(y);
694+ }
695+ return valDiff;
696+ });
697+ ```
698+
662699
663700### 1-5) Get sub array
664701``` java
Original file line number Diff line number Diff line change @@ -464,3 +464,48 @@ public String sort(String s) {
464464 return fleets;
465465 }
466466```
467+
468+
469+ ### 2-7) TopK Frequent Words
470+
471+ ``` java
472+ // java
473+ // LC 692
474+
475+ // V0-1
476+ // IDEA: Sort on map key set
477+ public List<String > topKFrequent_0_1(String [] words, int k) {
478+
479+ // IDEA: map sorting
480+ HashMap<String , Integer > freq = new HashMap<> ();
481+ for (int i = 0 ; i < words. length; i++ ) {
482+ freq. put(words[i], freq. getOrDefault(words[i], 0 ) + 1 );
483+ }
484+ List<String > res = new ArrayList (freq. keySet());
485+
486+ /**
487+ * NOTE !!!
488+ *
489+ * we directly sort over map's keySet
490+ * (with the data val, key that read from map)
491+ *
492+ *
493+ * example:
494+ *
495+ * Collections.sort(res,
496+ * (w1, w2) -> freq.get(w1).equals(freq.get(w2)) ? w1.compareTo(w2) : freq.get(w2) - freq.get(w1));
497+ */
498+ Collections . sort(res, (x, y) - > {
499+ int valDiff = freq. get(y) - freq. get(x); // sort on `value` bigger number first (decreasing order)
500+ if (valDiff == 0 ){
501+ // Sort on `key ` with `lexicographically` order (increasing order)
502+ // return y.length() - x.length(); // ?
503+ return x. compareTo(y);
504+ }
505+ return valDiff;
506+ });
507+
508+ // get top K result
509+ return res. subList(0 , k);
510+ }
511+ ```
You can’t perform that action at this time.
0 commit comments