LeetCode Notes: Weekly Contest 218 Contest Record

0. Summary after the game

Today is really capable of pissing me off!

It's my own death. I was too excited to play games with my buddies last night, and then couldn't sleep, so I opened a novel and read it casually, and then I saw it at 3:30. . .

Hehe, running to play the game with panda eyes, I really overestimate myself!

The result is that all kinds of boundary conditions are unclear, a huge waste of time, and it is particularly easy to make mistakes. The second question is directly wrong because of the boundary conditions twice, and the last question is directly wrong 5 times, 4 of which are because of not being wrong. Think about the boundary conditions!

It was abruptly pushed the time-consuming from about 1 hour to 1 hour 45 minutes. It was a frustration, but the ranking was unexpectedly not too hip, 123 in the country, 312 in the world, anyway, also in the front. 3%, but still not reconciled! ! !

Alas, it's such a simple topic, it's rare that you don't even have a hard topic. As a result, pulling the hips becomes such a virtue, it really is. . .

Sure enough, you can think clearly if you have a good rest, otherwise, even if you think you are awake, your mind will actually be muddled. . .

1. Topic One

The link to the question given for question one is as follows:

1. Problem-solving ideas

There is nothing to say about this question, just keep replacing the content.

2. Code implementation

The python code is directly given as follows:

class Solution:
    def interpret(self, command: str) -> str:
        command = command.replace("(al)", "al")
        command = command.replace("()", "o")
        return command

After submitting the code for evaluation, it took 28ms and took up 14.2MB of memory.

The current optimal solution takes 24ms, but after looking at the code, it is essentially the same as the above implementation, so I won’t do more here.

2. Topic 2

The link to the second question is given as follows:

1. Problem-solving ideas

The idea of ​​this question is also very straightforward, just count all the numbers in the array, and then examine the number of two-tuples that add up to k.

The only thing that needs attention is that the boundary conditions need to be paid attention to:

  • When i == k / 2, they need special investigation.

2. Code implementation

Given the python code implementation:

class Solution:
    def maxOperations(self, nums: List[int], k: int) -> int:
        counter = Counter(nums)
        ans = 0
        for i in counter:
            if i < k-i:
                ans += min(counter[i], counter[k-i])
            elif i == k-i:
                ans += counter[i] // 2
            else:
                continue
        return ans

After submitting the code evaluation, it took 632ms and took up 27.6MB of memory.

The current optimal code implementation takes 608ms, but in essence, the ideas of the two are exactly the same.

3. Topic Three

The link to the test questions for topic three is as follows:

1. Problem-solving ideas

The idea of ​​this question is actually quite simple, just based on the following formula:

( a + b )   m o d ( p ) = ( ( a 1 ⋅ p + a 2 ) + ( b 1 ⋅ p + b 2 ) )   m o d ( p ) = ( a 2 + b 2 )   m o d ( p ) = ( a   m o d ( p ) + b   m o d ( p ) )   m o d ( p ) \begin{aligned} (a + b) \ mod(p) &= ((a_1 \cdot p + a_2) + (b_1 \cdot p + b_2)) \ mod(p) \\ &= (a_2 + b_2) \ mod(p) \\ &= (a\ mod(p) + b\ mod(p))\ mod(p) \end{aligned} (a+b) mod(p)=((a1p+a2)+(b1p+b2) ) m o d ( p ) =(a2+b2) m o d ( p ) =(a mod(p)+b m o d ( p ) ) m o d ( p )  

Therefore, we only need to calculate the number of digits that need to be moved each time, and then perform a transformation on the previous answer and then find the next solution.

2. Code implementation

We give the python code implementation as follows:

class Solution:
    def concatenatedBinary(self, n: int) -> int:
        flag = 1
        logits = 0
        ans = 0
        MOD = 10**9 + 7
        for i in range(1, n+1):
            if i == flag:
                flag *= 2
                logits += 1
            ans = ((ans << logits) + i) % MOD
        return ans

After submitting the code for evaluation, it took 832ms and took up 14.2MB of memory.

The current optimal code implementation takes only 44ms, which has a performance improvement of more than an order of magnitude than ours. Therefore, we need to take a good look at its code implementation ideas.

3. Algorithm optimization

The current optimal code implementation, that is, the code of 44ms is a bit cumbersome, so I didn’t take a closer look, but it’s worth mentioning that another algorithm that takes 80ms has simply shattered my three views. In essence, theirs The approach is exactly the same as ours, but they use a caching mechanism, and then the wonderful effect of the model is increased by an order of magnitude, which is simply impossible to understand.

If any reader understands the mystery, please give guidance in the comment area, thank you!

Here, we only give the code implementation as follows:

memo={
    
    1:1}
mod=10**9+7
class Solution:
    def concatenatedBinary(self, n: int) -> int:
        if n in memo:
            return memo[n]
        pre=self.concatenatedBinary(n-1)
        ans=((pre<<(len(bin(n))-2))+n)%mod
        memo[n]=ans
        return ans

4. Topic Four

The link to the test question for question four is as follows:

1. Problem-solving ideas

The fourth question is my biggest failure in this competition.

How to put it, it's quite embarrassing. In principle, there should be a better and more elegant way to solve this problem. It should be possible to directly give the optimal data selection strategy in some way. Unfortunately, I haven't thought of it for a long time. All contain various problems.

Fortunately, the topic limits the complexity of the possibility, so I tried to use the most violent traversal method, that is, to traverse all the legal possibilities through the combination number. As a result, I still encountered various boundary problems and definitions. Wrong problem, abruptly wrong 4 times, and then encountered a timeout, and finally paid the price of 5 errors to finally solve the problem.

I really don't know how to react to this, alas. . .

Let's go back to the problem itself. If you use the combination number to traverse and solve this problem, there is not much to say. The python implementation is given below.

2. Code implementation

The python code is given as follows:

class Solution:
    def minimumIncompatibility(self, nums: List[int], k: int) -> int:
        n= len(nums)
        k = n // k
        
        if k == 1:
            return 0
        counter = Counter(nums)
        if any(x > n // k for x in counter.values()):
            return -1
        
        @lru_cache(None)
        def dp(idxs):
            if len(idxs) == k:
                num = [nums[i] for i in idxs]
                return math.inf if len(set(num)) != k else max(num) - min(num)
            ans = math.inf
            for tmp in combinations(idxs, k):
                num = [nums[i] for i in tmp]
                if len(set(num)) == k:
                    ans = min(ans, max(num) - min(num) + dp(tuple([idx for idx in idxs if idx not in tmp])))
            return ans
        
        ans = dp(tuple([i for i in range(n)]))
        return ans if ans != math.inf else -1

After submitting the code for evaluation, it took 7848ms and took up 25.8MB of memory.

The current optimal code implementation takes 1252ms, which is more than 5 times faster than ours, but the code is long enough, let's see if there are better ideas for solving problems later.

Guess you like

Origin blog.csdn.net/codename_cys/article/details/110881477