Cho một mảng số nguyên arr gồm n phần tử. Sắp xếp mảng theo số lần xuất hiện của các phần tử.
Ví dụ:
Input: arr[] = {2, 5, 2, 8, 5, 6, 8, 8}
Output: result = {6, 2, 5, 8}
Các bước:
| B1: Tạo class Element có 2 phần tử: value(giá trị của phần tử), count(số lần xuất hiện) B2: Sắp xếp mảng B3: Đếm số lần xuất hiện của mỗi phần tử trong mảng dựa vào class Element B4: Sắp xếp mảng Element theo số lần xuất hiện của mỗi phần tử |
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static class Element {
public int val = 0;
public int count = 0;
}
public static int[] sortByFrequency(int[] arr, int n) {
if (n == 0)
return arr;
Element[] elements = new Element[n];
int index = 0;
// Sắp xếp mảng
Arrays.sort(arr);
Element element = new Element();
element.val = arr[0];
element.count++;
elements[index] = element;
// Đếm số lần xuất hiện của một phần tử trong mảng
for (int i = 1; i < n; i++) {
if (element.val != arr[i]) {
index++;
element = new Element();
element.val = arr[i];
element.count++;
elements[index] = element;
} else {
element.count++;
}
}
// Sắp xếp mảng dựa trên số lần xuất hiện
Arrays.sort(elements, 0, index + 1, Comparator.comparingInt(o -> o.count));
// trả về kết quả mảng được sắp xếp tăng dần theo số lần xuất hiện
int[] result = new int[index + 1];
for (int i = 0; i < index + 1; i++) {
result[i] = elements[i].val;
}
return result;
}
public static void main(String[] args) {
int[] arr = {2, 5, 2, 8, 5, 6, 8, 8};
int[] result = sortByFrequency(arr, arr.length);
for (int val : result) {
System.out.println(val + " ");
}
}
}
Output: 6, 2, 5, 8
Độ phức tạp: O(nlogn)
Link đề bài: https://www.geeksforgeeks.org/sort-elements-by-frequency/