LeetCode Notes: Weekly Contest 226 Contest Record

0. Summary after the game

The results of this competition can only be said to be quite contrasting. This weekend is considered to be one of the most decadent weekends I have ever had. Obviously there are so many things I want to do, but I took them all to watch the variety show. Two days Almost sleeplessly watching all the plots of Ace vs. Ace for the entire 5 seasons, it is really crazy...

The result is that I feel very guilty now. This is still the situation when I am still single. I really can’t figure out how those who have girlfriends balance work, study and life. I have tortured myself exhausted by work and study alone. Exhausted, although in fact I think I still spent a lot of absolute time on rest, but the feeling of guilt has almost crushed me. Alas, I have gradually become incoherent and I don’t know what I’m talking about. I think the future I'd better go to see a psychologist at some time. It was probably my biggest mistake that year when I didn't see a psychologist regularly at school...

The only thing I’m satisfied with this week is the result of this week’s competition. I have finished all 4 questions in about half an hour, and then I am in the top 100 in the world. This is about the second time I got it. Such a high ranking, it should have been a very happy thing, alas...

1. Topic One

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

1. Problem-solving ideas

If this problem is solved mathematically, it should be quite difficult. However, my solution here is more violent. I directly add the digits of each number in the range according to the meaning of the problem. Just count it.

2. Code implementation

The python code is given as follows:

class Solution:
    def countBalls(self, lowLimit: int, highLimit: int) -> int:
        def fn(x):
            res = 0
            while x != 0:
                res += x % 10
                x = x // 10
            return res
        cnt = defaultdict(int)
        for i in range(lowLimit, highLimit+1):
            cnt[fn(i)] += 1
        return max(cnt.values())

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

Belongs to the current best code implementation.

2. Topic 2

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

1. Problem-solving ideas

The idea of ​​this question is actually quite straightforward. Obviously, if all the adjacent relations are given, the first element will inevitably only appear once. Therefore, counting the number of occurrences can determine the first and last elements, and take one of the two as the first. Elements are sufficient.

Later we only need to get all the elements through a chain transformation.

2. Code implementation

The python code is given as follows:

class Solution:
    def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
        pair = defaultdict(list)
        n = len(adjacentPairs)
        for x, y in adjacentPairs:
            pair[x].append(y)
            pair[y].append(x)
        st = sorted(pair.keys(), key=lambda x: len(pair[x]))[0]
        res = [st]
        seen = {
    
    st}
        for i in range(n):
            nxt = [x for x in pair[res[-1]] if x not in seen][0]
            seen.add(nxt)
            res.append(nxt)
        return res

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

The current optimal algorithm takes 1084ms to implement, but the algorithm ideas are the same.

3. Topic Three

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

1. Problem-solving ideas

We consider each query, if it can be done, the necessary and sufficient conditions are:

  1. When one eats one per day, the number of apples under the favorite candy type is not 0 when the target number of days is reached;
  2. In the case of eating the maximum number of candies every day, you will not be late for the target candies by the end of the target number of days;

Therefore, we only need to perform a cumulative sum of the number of candies in advance to quickly solve this problem.

The only thing to note is that the conditions of the subject start from day 0...

2. Code implementation

The python code is given as follows:

class Solution:
    def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:
        cumsum = [0] + list(accumulate(candiesCount))
        
        def fn(query):
            idx, d, cap = query
            if d >= cumsum[idx+1]:
                return False
            elif (d+1) * cap <= cumsum[idx]:
                return False
            return True
        
        return [fn(query) for query in queries]

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

The most current code implementation takes 1464ms, but the algorithm ideas are the same.

4. Topic Four

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

1. Problem-solving ideas

There is probably a more elegant solution to this problem, but here is a pseudo-dynamic programming algorithm that uses a cache method and recursive relations. It basically looks like a spike, and there is not much to say. It will be clear if you look at it. Up...

2. Code implementation

The python code is given as follows:

class Solution:
    def checkPartitioning(self, s: str) -> bool:
        n = len(s)
        
        @lru_cache(None)
        def dp(idx, k):
            if k == 1:
                sub = s[idx:]
                return sub == sub[::-1]
            elif idx >= n:
                return False
            for j in range(idx+1, n):
                sub = s[idx: j]
                if sub == sub[::-1] and dp(j, k-1):
                    return True
            return False
        
        return dp(0, 3)

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

Guess you like

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