Repository navigation
Expand file tree
/
Copy pathLeetCode1636.java
More file actions
59 lines (49 loc) · 2.27 KB
/
Copy pathLeetCode1636.java
File metadata and controls
59 lines (49 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
//1636. Sort Array by Increasing Frequency
public class LeetCode1636 {
//Better approach
public int[] frequencySort(int[] nums) {
// 1. Build an int-based frequency map using summingInt
Map<Integer, List<Integer>> countMap = Arrays.stream(nums)
.boxed()
.collect(Collectors.groupingBy(Function.identity()));
// 2. Sort by frequency ascending, then by value descending for ties
return countMap.entrySet()
.stream()
.sorted(Comparator.<Map.Entry<Integer,List<Integer>>>comparingInt( entry -> entry.getValue().size())
.thenComparing( Map.Entry::getKey,Comparator.reverseOrder()))
.flatMap( entry -> entry.getValue().stream())
.mapToInt(Integer::intValue)
.toArray();
}
public int[] frequencySort_1(int[] nums) {
// 1. Build an int-based frequency map using summingInt
Map<Integer, Integer> countMap = Arrays.stream(nums)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));
// 2. Sort by frequency ascending, then by value descending for ties
return Arrays.stream(nums)
.boxed()
.sorted(Comparator.comparingInt((Integer n) -> countMap.get(n))
.thenComparing(Comparator.reverseOrder()))
.mapToInt(i -> i)
.toArray();
}
public int[] frequencySort_2(int[] nums) {
// 1. Build an int-based frequency map using summingInt
Map<Integer, List<Integer>> countMap = Arrays.stream(nums)
.boxed()
.collect(Collectors.groupingBy(Function.identity()));
// 2. Sort by frequency ascending, then by value descending for ties
return countMap
.values()
.stream()
.sorted((list1, list2) ->
list1.size() != list2.size() ? Integer.compare(list1.size(), list2.size()) : Integer.compare(list2.getFirst(), list1.getFirst()))
.flatMap(List::stream)
.mapToInt(i -> i)
.toArray();
}
}