Skip to content

Commit 8ae5968

Browse files
author
xiaolingtong@bilibili.com
committed
greedy
1 parent 2619d52 commit 8ae5968

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

note/1733/README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# [Minimum Number of People to Teach][title]
2+
3+
## Solution
4+
贪心的思想,找到没有共同语言可以沟通的朋友 减去 这群人中大家会的课数最多的数目就是需要教的最大数目了
5+
6+
```
7+
class Solution {
8+
private fun hasCommon(languages: Array<IntArray>, friend1: Int, friend2: Int): Boolean {
9+
val x = languages[friend1 - 1]
10+
val y = languages[friend2 - 1]
11+
return x.any { y.contains(it) }
12+
}
13+
14+
fun minimumTeachings(n: Int, languages: Array<IntArray>, friendships: Array<IntArray>): Int {
15+
val mostLanguages = IntArray(n)
16+
val noConnects = mutableSetOf<Int>()
17+
for ((friend1, friend2) in friendships) {
18+
if (!hasCommon(languages, friend1, friend2)) {
19+
noConnects.add(friend1)
20+
noConnects.add(friend2)
21+
}
22+
}
23+
for (noConnectMan in noConnects) {
24+
languages[noConnectMan - 1].forEach {
25+
mostLanguages[it - 1]++
26+
}
27+
}
28+
val max = mostLanguages.maxOrNull() ?: 0
29+
return noConnects.size - max
30+
}
31+
}
32+
```
33+
## Conclusion
34+
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-kotlin-leetcode][akl]
35+
36+
[title]: https://leetcode.cn/problems/minimum-number-of-people-to-teach/description/?company_slug=duo-lin-guo
37+
[akl]: https://github.com/NightXlt/awesome-kotlin-leetcode
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.blankj.medium._1733
2+
3+
4+
class Solution {
5+
private fun hasCommon(languages: Array<IntArray>, friend1: Int, friend2: Int): Boolean {
6+
val x = languages[friend1 - 1]
7+
val y = languages[friend2 - 1]
8+
return x.any { y.contains(it) }
9+
}
10+
11+
fun minimumTeachings(n: Int, languages: Array<IntArray>, friendships: Array<IntArray>): Int {
12+
val mostLanguages = IntArray(n)
13+
val noConnects = mutableSetOf<Int>()
14+
for ((friend1, friend2) in friendships) {
15+
if (!hasCommon(languages, friend1, friend2)) {
16+
noConnects.add(friend1)
17+
noConnects.add(friend2)
18+
}
19+
}
20+
for (noConnectMan in noConnects) {
21+
languages[noConnectMan].forEach {
22+
mostLanguages[it]++
23+
}
24+
}
25+
val max = mostLanguages.maxOrNull() ?: 0
26+
return noConnects.size - max
27+
}
28+
}

0 commit comments

Comments
 (0)