# 第 277 场周赛题解 (opens new window)

# Q1 2148. 元素计数 (opens new window)

这阅读理解... 就是非最大最小值的数量。

class SolutionA {
    fun countElements(nums: IntArray): Int {
//        val max = nums.max()!!
        val max = nums.maxOrNull()!!
//        val min = nums.min()!!
        val min = nums.maxOrNull()!!
        return nums.count { it != max && it != min }
    }
}
1
2
3
4
5
6
7
8
9

# Q2 2149. 按符号重排数组 (opens new window)

模拟,按符号分成两个数组再按顺序合并。

class SolutionB {
    fun rearrangeArray(nums: IntArray): IntArray {
        val a = nums.filter { it < 0 }
        val b = nums.filter { it > 0 }
        val ans = ArrayList<Int>()
        for (i in a.indices) {
            ans.add(b[i])
            ans.add(a[i])
        }
        return ans.toIntArray()
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

# Q3 2150. 找出数组中的所有孤独数字 (opens new window)

模拟。

class SolutionC {
    fun findLonely(nums: IntArray): List<Int> {
        val map = IntArray(1000005)
        nums.forEach {
            map[it]++
        }
        val ans = arrayListOf<Int>()
        for (i in map.indices) {
            if (map[i] == 1 &&
                (i + 1 !in map.indices || map[i + 1] == 0) &&
                (i - 1 !in map.indices || map[i - 1] == 0)
            ) {
                ans.add(i)
            }
        }
        return ans
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# Q4 2151. 基于陈述统计最多好人数 (opens new window)

被二进制的运算坑了... 取第ii位是00还是11,取乱了,直接改字符串一次就过了... 以后直接用字符串好了...

// 状态压缩
// 二进制
// 能用字符串就直接用字符串吧...
class SolutionD {
    fun maximumGood(statements: Array<IntArray>): Int {
        val n = statements.size
        fun check(mask: Int): Boolean {
//            val m = mask.toString(2).padStart(n, '0')
            for (i in statements.indices) {
                // 只管好人说的话 有没有悖论
                // 假设第i个人是好人
//                if (m[i] != '0') {
                if ((mask shr i) and 1 != 0) {
                    for (j in statements[i].indices) {
                        // i 认为 j 是好人
//                        if (statements[i][j] == 1 && m[j] == '0') {
                        if (statements[i][j] == 1 && (mask shr j) and 1 == 0) {
                            return false
                        }
                        // i 认为 j 是坏人
//                        if (statements[i][j] == 0 && m[j] == '1') {
                        if (statements[i][j] == 0 && (mask shr j) and 1 == 1) {
                            return false
                        }
                    }
                }
            }
            return true
        }

        var ans = 0
        for (mask in 0 until (1 shl n)) {
            // 1是好人 0是坏人
            val m = mask.toString(2).padStart(n, '0')
            if (check(mask)) {
                ans = maxOf(ans, m.count { it == '1' })
            }
        }
        return ans
    }
}
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