MAP - Sort with stream

 LEETCODE 1636

Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.

Return the sorted array.

Example 1:

Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.

Example 2:

Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.

Example 3:

Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]

#1

class Solution { public int[] frequencySort(int[] nums) { return Arrays.stream(nums) .boxed() // boxing to wapped class .collect(Collectors.toMap(e-> e , e-> 1 , Integer::sum))//?? .entrySet() .stream() .sorted((e1,e2) -> e1.getValue().equals(e2.getValue()) ? e2.getKey().compareTo(e1.getKey()) : e1.getValue().compareTo(e2.getValue())) .flatMap(e-> Stream.iterate(e.getKey(), n->n).limit(e.getValue())) .mapToInt(e->e) .toArray(); } }


#2

class Solution { int i = 0; public int[] frequencySort(int[] nums) { Arrays.stream(nums).boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet().stream() .sorted((x1, x2) -> x1.getValue() == x2.getValue() ? x2.getKey() - x1.getKey() : (int) (x1.getValue() - x2.getValue())) .forEach(x -> Stream.iterate(0, n -> n + 1).limit(x.getValue()).forEach(n -> nums[i++] = x.getKey())); return nums; } }


留言

此網誌的熱門文章

JAVA - DSF Example