-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1338-ReduceArraySizeToTheHalf.go
More file actions
85 lines (75 loc) · 2.73 KB
/
1338-ReduceArraySizeToTheHalf.go
File metadata and controls
85 lines (75 loc) · 2.73 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
// 1338. Reduce Array Size to The Half
// You are given an integer array arr.
// You can choose a set of integers and remove all the occurrences of these integers in the array.
// Return the minimum size of the set so that at least half of the integers of the array are removed.
// Example 1:
// Input: arr = [3,3,3,3,5,5,5,2,2,7]
// Output: 2
// Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
// Possible sets of size 2 are {3,5},{3,2},{5,2}.
// Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.
// Example 2:
// Input: arr = [7,7,7,7,7,7]
// Output: 1
// Explanation: The only possible set you can choose is {7}. This will make the new array empty.
// Constraints:
// 2 <= arr.length <= 10^5
// arr.length is even.
// 1 <= arr[i] <= 10^5
import "fmt"
import "sort"
func minSetSize(arr []int) int {
mp, count := make(map[int]int), []int{}
for _, v := range arr { // 统计出现次数
mp[v]++
}
for _, v := range mp {
count = append(count, v)
}
sort.Ints(count)
n, m, sum := len(arr), len(count), 0
for i := m - 1; i >= 0; i --{
sum += count[i]
if sum >= n / 2 { // 超过一半元素了
return m - i
}
}
return n / 2 // 处理无数值重复的情况
}
func minSetSize1(arr []int) int {
mx := 0
for _, v := range arr { // 找出最大值
if v > mx { mx = v }
}
count := make([]int, mx + 1)
for _, v := range arr {
count[v]++
}
sort.Slice(count, func(i, j int) bool { // 从大到小排序
return count[i] > count[j]
})
res, sum, n := 0, 0, len(arr)
for i, v := range count {
if sum >= n / 2 { break } // 超过一半
sum += v
res = i + 1
}
return res
}
func main() {
// Example 1:
// Input: arr = [3,3,3,3,5,5,5,2,2,7]
// Output: 2
// Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
// Possible sets of size 2 are {3,5},{3,2},{5,2}.
// Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.
fmt.Println(minSetSize([]int{3,3,3,3,5,5,5,2,2,7})) // 2
// Example 2:
// Input: arr = [7,7,7,7,7,7]
// Output: 1
// Explanation: The only possible set you can choose is {7}. This will make the new array empty.
fmt.Println(minSetSize([]int{7,7,7,7,7,7})) // 1
fmt.Println(minSetSize1([]int{3,3,3,3,5,5,5,2,2,7})) // 2
fmt.Println(minSetSize1([]int{7,7,7,7,7,7})) // 1
}