# 第 41 场双周赛题解

# Q1 1684. 统计一致字符串的数目 (opens new window)

模拟。

class Solution1684 {
    fun countConsistentStrings(allowed: String, words: Array<String>): Int {
        return words.count { it.all { it in allowed } }
    }
}
1
2
3
4
5

# Q2 1685. 有序数组中差绝对值之和 (opens new window)

数学。每前进一步,右侧部分减少差值,左侧部分增加差值。

class Solution1685 {
    fun getSumAbsoluteDifferences(nums: IntArray): IntArray {
        val n = nums.size
        var cur = nums.sum()
        cur -= n * nums[0]
        val ans = arrayListOf<Int>()
        for (i in nums.indices) {
            if (i > 0) {
                cur += (2 * i - n) * (nums[i] - nums[i - 1])
            }
            ans.add(cur)
        }
        return ans.toIntArray()
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# Q3 1686. 石子游戏 VI (opens new window)

石头的总价值是A的价值+B的价值,逆序排序后依次拿当前最高价值的。注意最后计算时比较的不是算总价值的和。

class Solution1686 {
    fun stoneGameVI(aliceValues: IntArray, bobValues: IntArray): Int {
        val c = ArrayList<Pair<Int, Int>>()
        for (i in aliceValues.indices) {
            c.add(Pair(i, aliceValues[i] + bobValues[i]))
        }
        var a = 0
        var b = 0
        c.sortedByDescending { it.second }.forEachIndexed { index, i ->
            if (index % 2 == 0) {
                a += aliceValues[i.first]
            } else {
                b += bobValues[i.first]
            }
        }
        return if (a == b) 0 else if (a > b) 1 else -1
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# Q4 1687. 从仓库到码头运输箱子 (opens new window)


1