-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathequalizeArray.ts
More file actions
59 lines (43 loc) · 1.52 KB
/
Copy pathequalizeArray.ts
File metadata and controls
59 lines (43 loc) · 1.52 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
/*
Given an array of integers, determine the minimum number of elements to delete to leave only elements of equal value.
Example
arr = [1, 2, 2, 3]
Delete the 2 elements 3 and 1 leaving 2. If both twos plus either the 1 or the 3 are deleted, it takes 2 deletions to leave either [3] or [1]. The minimum number of deletions is 2.
Function Description
Complete the equalizeArray function in the editor below.
equalizeArray has the following parameter(s):
int arr[n]: an array of integers
Returns
int: the minimum number of deletions required
Input Format
The first line contains an integer , the number of elements in .
The next line contains space-separated integers .
Constraints
Sample Input
STDIN Function
----- --------
5 arr[] size n = 5
3 3 2 1 3 arr = [3, 3, 2, 1, 3]
Sample Output
2
*/
// We create the map to save the number of repeat times of each element in the array
// Then we will find the largest repeating times
// The different between the length and the largest repeating times is the minimum number need to be deleted.
function equalizeArray(arr: number[]) {
const map = new Map<number, number>();
let maxRepeatingTime = 0;
const length = arr.length;
for (let i = 0; i < arr.length; i++) {
if (map.has(arr[i])) {
map.set(arr[i], map.get(arr[i]) + 1);
} else {
map.set(arr[i], 1);
}
if (maxRepeatingTime < map.get(arr[i])) {
maxRepeatingTime = map.get(arr[i]);
}
}
return length - maxRepeatingTime;
}
console.log(equalizeArray([3, 3, 2, 1, 3]));