LeetCode Biweekly Competition 106 (2023/06/10) Two Thinking Questions

This article has included AndroidFamily , technical and workplace issues, please pay attention to the official account [Peng Xurui] and join Knowledge Planet to ask questions.

Biweekly 106 Overview

T1. Judging whether a number is charming (Easy)

  • Tags: count

T2. Find the longest semi-repeated substring (Medium)

  • Tags: same direction double pointer

T3. Mobile robot (Medium)

  • Labels: brain teasers, sorting

T4. Find a good subset of the matrix (Hard)

  • Tags: hash table, greedy


T1. Judging whether a number is charming (Easy)

https://leetcode.cn/problems/check-if-the-number-is-fascinating/description/

Solution 1 (counting)

  • Calculate the number after splicing, and check whether the number of numbers 1 to 9 is 1, you can use string comparison to simulate counting;
  • Observing the numerical law, the valid range of legal n is [123, 329].
class Solution {
    
    
    fun isFascinating(n: Int): Boolean {
    
    
        if (n !in 123..329) return false
        return "123456789" == "$n${
      
      2*n}${
      
      3*n}".asSequence().sorted().joinToString("")
    }
}

Complexity analysis:

  • Time complexity: O(UlgU) U is the maximum length of a single number
  • Space complexity: O(U)

Problem Solution 2 (Tabulation)

There are only 4 charming numbers in the topic range.

class Solution {
    
    
    fun isFascinating(n: Int): Boolean {
    
    
        return n in arrayOf(192, 219, 273, 327)
    }
}

Complexity analysis:

  • Time complexity: O(1)
  • Space complexity: O(1)

T2. Find the longest semi-repeated substring (Medium)

https://leetcode.cn/problems/find-the-longest-semi-repetitive-substring/

Problem solution (same direction double pointer)

Maintain the sliding window, if the right pointer is the same as the previous position, it means adding an adjacent duplicate pair.

When the adjacent repeated pair repeatCnt is greater than 1, the left pointer needs to be shrunk at this time. If the left pointer is the same as the last position on the right, it means to reduce an adjacent repeated pair (because the left pointer cannot exceed the window when repeatCnt is greater than 1, it is not necessary Check that the left pointer moves out of bounds).

class Solution {
    
    
    fun longestSemiRepetitiveSubstring(s: String): Int {
    
    
        val n = s.length
        var ret = 0
        var i = 0
        var repeatCnt = 0
        for (j in 0 until n) {
    
    
            // 移动右指针
            if (j > 0 && s[j] == s[j - 1]) repeatCnt ++
            while (repeatCnt > 1) {
    
    
                // 移动左指针
                if (s[i] == s[i + 1]) repeatCnt --
                i++
            }
            // 记录结果
            ret = Math.max(ret, j - i + 1)
        }
        return ret
    }
}

Complexity analysis:

  • Time complexity: O(n)
  • Space complexity: O(1)

T3. Mobile robot (Medium)

https://leetcode.cn/problems/movement-of-robots/

Problem solving (simulation + sorting)

Notice that when a collision occurs and the direction of the robot is changed, we can reverse the identity of the robot. At this time, it is equivalent to no collision and the robot is traveling in the normal direction, so we can directly ignore the collision rules, calculate the final position of the robot and calculate the pairwise distance .

To calculate the pairwise distance, we first sort all the points. Since the distance formula of two robots is x - y, then for each robot nums[i], in the distance formula, it will be added as i times x and solved as (n -1 - i) times y, which can be Enumerate the contribution of each robot to the distance formula to calculate the overall pairwise distance sum.

class Solution {
    
    
    fun sumDistance(nums: IntArray, s: String, d: Int): Int {
    
    
        val n = nums.size
        val MOD = 1000000007
        // 移动(忽视碰撞)
        for (i in nums.indices) {
    
    
            nums[i] += if (s[i] == 'R') d else -d
        }
        // 排序
        nums.sort()
        // 计算两两距离
        var ret = 0L
        for (i in nums.indices) {
    
    
            ret = (ret + (2L * i - n + 1) * nums[i]) % MOD
        }
        return ret.toInt()
    }
}

Complexity analysis:

  • Time complexity: O(nlgn) bottleneck is sorting
  • Space complexity: O(lgn)

Similar topics:


T4. Find a good subset of the matrix (Hard)

https://leetcode.cn/problems/find-a-good-subset-of-the-matrix/

Problem solution (hash + greedy)

It is easy to think that we need to select those rows that are relatively sparse (but not necessarily the sparsest row), and repeatedly selecting the exact same row will not have value for the result, so we first deduplicate the row.

Since the question has only 5 columns at most, there are only 2^5=32 row types at most. It can be proved that when the question is n = 5, the effective solution is only 2 rows at most.

class Solution {
    
    
    fun goodSubsetofBinaryMatrix(grid: Array<IntArray>): List<Int> {
    
    
        val n = grid.size
        val m = grid[0].size
        // 分组
        val U = 32 // 0 - 31
        val indexs = IntArray(U) {
    
     -1 }
        for ((i, row) in grid.withIndex()) {
    
    
            var mask = 0
            for ((j, e) in row.withIndex()) {
    
    
                mask = mask or (e shl j)
            }
            indexs[mask] = i
        }
        // 全 0
        if (-1 != indexs[0]) return listOf(indexs[0])
        // 贪心
        for (x in 1 until U) {
    
    
            for (y in 1 until U) {
    
    
                // 过滤
                if (-1 == indexs[x] || -1 == indexs[y]) continue
                // 是否互补
                if (x and y == 0) return listOf(indexs[x], indexs[y]).sorted()
            }
        }
        return Collections.emptyList()
    }
}

Complexity analysis:

  • Time complexity: O(n + U^2) U = 32
  • Space complexity: O(U)

Past review

Guess you like

Origin blog.csdn.net/pengxurui/article/details/131154389