LeetCode Notes: Weekly Contest 228 Contest Record

0. Summary after the game

I didn’t really want to play in the third day of the Lunar New Year. Recently, due to some reasons, I felt that my state was in a relatively low state. It is estimated that I will not get any good rankings in the game, but I am afraid that I will let myself go. Will take this kind of giving up as the norm, so in the end he still gritted his teeth and played the game. Fortunately, I was lucky, and in the end all 4 questions were completed. Although the last question was very stupid and superfluous, which caused continuous overtime to affect the final ranking, in the end, the results of all 4 questions were not much worse. Anyway, personally, it's a comforting place...

By the way, it’s definitely not because I played high during the New Year and I forgot about it...

1. Topic One

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

1. Problem-solving ideas

The idea of ​​this question is quite straightforward, because the final result is either 0101a repeated string or 1010a repeated string.

Therefore, we only need to examine the number of operations that need to be experienced in the following two cases and then take the smaller number to get the final result.

2. Code implementation

The python code is given as follows:

class Solution:
    def minOperations(self, s: str) -> int:
        odd = 0
        even = 0
        for i, c in enumerate(s):
            if i % 2 == 0:
                if c == "0":
                    even += 1
                else:
                    odd += 1
            else:
                if c == "1":
                    even += 1
                else:
                    odd += 1
        return min(odd, even)

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

2. Topic 2

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

1. Problem-solving ideas

This question was a bit tricky at first, but it is actually quite straightforward to think about it later, that is, first count the number of consecutive occurrences of the same character, and then calculate the number of repetitions separately.

Obviously, for a continuous substring with a repetition number of n and a length of l, the number of isomorphic strings contained in it is n ⋅ k ⋅ (k + 1) 2 n\cdot \frac{k\cdot(k +1)}{2}n2k(k+1)

Therefore, we can quickly give our final code implementation as follows.

2. Code implementation

The python code is given as follows:

class Solution:
    def countHomogenous(self, s: str) -> int:
        MOD = 10**9+7
        cache = {
    
    }
        cnt = 0
        for idx, c in enumerate(s):
            if idx == 0:
                cnt += 1
            else:
                last = s[idx-1]
                if c == last:
                    cnt += 1
                else:
                    if last not in cache:
                        cache[last] = {
    
    }
                    if cnt not in cache[last]:
                        cache[last][cnt] = 0
                    cache[last][cnt] += 1
                    cnt = 1
        last = s[-1]
        if last not in cache:
            cache[last] = {
    
    }
        if cnt not in cache[last]:
            cache[last][cnt] = 0
        cache[last][cnt] += 1
        # print(cache)
        res = 0
        for item in cache.values():
            for cnt, repeat in item.items():
                res = (res + repeat * cnt * (cnt+1) // 2) % MOD
        return res

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

3. Topic Three

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

1. Problem-solving ideas

The first idea after getting this question is to try to use the greedy method to investigate how to divide the balls in the bag, and try to get the largest number of balls directly within the number of priority operations.

However, it was later discovered that Greedy's idea seemed infeasible, because how the balls in each bag should be divided depends on the number of balls in other bags and the maximum number of operations allowed.

Therefore, we can only change our thinking and use the dichotomy to search for the answer directly, and the test can be passed at this time.

2. Code implementation

The python code is given as follows:

class Solution:
    def minimumSize(self, nums: List[int], maxOperations: int) -> int:
        _min = 1
        _max = max(nums)
        nums = Counter(nums)
        
        def count_op(nums, tgt):
            res = 0
            for n, t in nums.items():
                res += t * ((n-1) // tgt)
            return res
        if count_op(nums, _min) <= maxOperations:
            return _min
        while _min < _max-1:
            m = (_min + _max) // 2
            if count_op(nums, m) <= maxOperations:
                _max = m
            else:
                _min = m
        return _max

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

4. Topic Four

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

1. Problem-solving ideas

The idea of ​​this question was right at the beginning, but I didn't think about the details of the implementation very clearly, which resulted in a timeout n times at the beginning, and after barely passing it, the operating efficiency was also terrible.

The most pitted thing is that I finally found that there is only one sort difference between my solution and the current optimal algorithm implementation. It really collapsed in an instant...

Not much to say, let’s just talk about the solution. In fact, it is quite simple. It is to count all the elements that can form a connected triple, and then find the smallest value after calculating its degree.

Therefore, we only need to record the connection nodes of all nodes first, then find the nodes connected to both nodes for the two nodes of each edge, and then calculate the degree.

It's just that if you traverse all edges, you can pass, but the efficiency is too low, but if you sort according to the degree of connection of each node first, you can optimize the execution efficiency of the program and increase the overall execution efficiency by more than an order of magnitude.

2. Code implementation

Here, we will not give our code, and directly give the best code implementation in the official website as follows.

class Solution:
    def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:
        graph=collections.defaultdict(set)
        for x,y in edges:
            graph[x].add(y)
            graph[y].add(x)
        nds=sorted([[len(graph[x]),x] for x in graph])
        nnds=sorted([[len(graph[x])+len(graph[y]),x,y] for x,y in edges])
        ans=3*n*(n-1)
        for w0,x,y in nnds:
            if w0>=ans:
                break
            for w1,z in nds:
                if w0+w1>=ans:
                    break
                if z in graph[x] and z in graph[y]:
                    ans=min(ans,w0+w1)
                    break
        return ans-6 if ans<3*n*(n-1) else -1

As mentioned earlier, the above code has two more sorts than our implementation, and then the execution efficiency is improved by more than one order of magnitude.

In the end, the code evaluation was submitted: it took 648ms and occupies 51MB of memory.

Guess you like

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