0216leetcode brushes 5 questions in python

38

Title description:
Given a positive integer n, output the nth item of the appearance sequence.
"Appearance sequence" is a sequence of integers, starting from the number 1, each item in the sequence is a description of the previous item.
You can think of it as a sequence of numeric strings defined by a recursive formula:
countAndSay(1) = “1”
countAndSay(n) is a description of countAndSay(n-1), and then converted into another numeric string.
The first five items are as follows:

  1. 1
    
  2. 11
    
  3. 21
    
  4. 1211
    
  5. 111221
    

The first item is the number 1 to
describe the previous item. This number is 1 which means "one 1", which is recorded as "11" to
describe the previous item. This number is 11 which means "two 1s", which is recorded as "21" to
describe the previous one. Item, this number is 21, that is, "one 2 + one 1", recorded as "1211" to
describe the previous item, this number is 1211, that is, "one 1 + one 2 + two 1s", recorded as "111221"

To describe a string of numbers, first divide the string into a minimum number of groups, each of which consists of a continuous maximum of the same characters. Then for each group, first describe the number of characters, and then describe the characters to form a description group. To convert the description into a numeric string, first replace the number of characters in each group with a number, and then connect all the description groups.

Example:
Insert picture description here
Answer:

class Solution:
    def countAndSay(self, n: int) -> str:
        #迭代方法
        s = "1"
        for i in range(n - 1):
            t = ""
            i, j, count = 0, len(s), 1
            while i < j - 1:
                if s[i] == s[i + 1]:
                    count += 1
                    i += 1
                else:
                    t = t + str(count) + s[i]
                    count = 1
                    i += 1
            s = t + str(count) + s[i]
        return s

59

Title description:
Give you a positive integer n and generate an nxn square matrix matrix containing all elements from 1 to n2 and the elements are arranged spirally in clockwise order.

Example:
Insert picture description here
Answer:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        maxtrix = [[0] * n for _ in range(n)]

        x_min, x_max = 0, n - 1
        y_min, y_max = 0, n - 1
        x, y = 0, 0
        dx, dy = 0, 1
        for i in range(n * n):
            maxtrix[x][y] = i + 1

            if y + dy > y_max:  # top right
                x_min += 1
                dx, dy = 1, 0
            elif x + dx > x_max:  # bottom right
                y_max -= 1
                dx, dy = 0, -1
            elif y + dy < y_min:  # bottom left
                x_max -= 1
                dx, dy = -1, 0
            elif x + dx < x_min:  # top left
                y_min += 1
                dx, dy = 0, 1
                
            x += dx
            y += dy

        return maxtrix

146

Topic description:
Design and implement an LRU (least recently used) caching mechanism using the data structure you have mastered.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with a positive integer as capacity capacity
int get(int key) If the keyword key exists in the cache, then return the value of the keyword, otherwise return -1.
void put(int key, int value) If the keyword already exists, change its data value; if the keyword does not exist, insert the set of "keyword-value". When the cache capacity reaches the upper limit, it should delete the oldest unused data value before writing new data to make room for the new data value.

Example:
Insert picture description here
Answer:

class LRUCache:

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = {
    
    }


    def get(self, key: int) -> int:
        # 搜索不到返回-1
        if key not in self.cache:
            return -1
        # 取出缓存中的key并赋值
        self.cache[key] = self.cache.pop(key)
        return self.cache[key]


    def put(self, key: int, value: int) -> None:
        # 如存在就先删除key
        if key in self.cache:
            self.cache.pop(key)
        self.cache[key] = value
       # 取缓存列表中最先进入的key
        if len(self.cache) > self.capacity:
            x = list(self.cache)[0]
            self.cache.pop(x)



# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

485

Title description:
Given a binary array, calculate the maximum number of consecutive 1s.

Example:
Insert picture description here
Answer:

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        cnt,res=0,0
        for i in nums:
            if i==1:
                cnt+=1
                res=max(cnt,res)
            else:
                cnt=0
        return res

561

Title description:
Given an integer array nums with a length of 2n, your task is to divide these numbers into n pairs, such as (a1, b1), (a2, b2), …, (an, bn) so that from 1 to n The sum of min(ai, bi) is the largest.
Return the maximum sum.

Example:
Insert picture description here
Answer:

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        return sum(sorted(nums)[::2])

Guess you like

Origin blog.csdn.net/yeqing1997/article/details/113813532