0215leetcode brushes 5 python questions

171

Title description:
Given a column name in an Excel table, return its corresponding column number.
For example,
A -> 1
B -> 2
C -> 3

Z -> 26
AA -> 27
AB -> 28

Example:
Insert picture description here
Answer:

class Solution:
    def titleToNumber(self, s: str) -> int:
        #26进制转10进制
        ans = 0
        for x in s:
            ans *= 26
            ans += ord(x)-ord('A')+1
        return ans

239

Title description:
Give you an integer array nums, a sliding window of size k moves from the leftmost side of the array to the rightmost side of the array. You can only see the k numbers in the sliding window. The sliding window only moves one position to the right at a time.
Returns the maximum value in the sliding window.

Example:
Insert picture description here

answer:

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        win, ret = [], []
        for i, v in enumerate(nums):
            if i >= k and win[0] <= i - k: 
                win.pop(0)
            while win and nums[win[-1]] <= v: 
                win.pop()
            win.append(i)
            if i >= k - 1: 
                ret.append(nums[win[0]])
        return ret

448

Title description:
Given an integer array with a range of 1 ≤ a[i] ≤ n (n = array size), some elements in the array appear twice, and some only appear once.
Find all the numbers in the range [1, n] that do not appear in the array.
Can you accomplish this task without using extra space and the time complexity is O(n)? You can assume that the returned array is not included in the extra space.

Example:
Insert picture description here
Answer:

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        '''
        将所有正数作为数组下标,置对应数组值为负值。
        那么,仍为正数的位置即为(未出现过)消失的数字。
        '''
        for num in nums:
            nums[abs(num)-1] = -abs(nums[abs(num)-1])
        print(nums)
        return [i+1 for i,num in enumerate(nums) if num>0]

765

Title description:
N couples sit on 2N consecutive seats and want to hold each other's hand. Calculate the minimum number of exchanges of seats so that each couple can sit side by side. Any two people can be selected for one exchange, and they can stand up and exchange seats.
People and seats are represented by integers from 0 to 2N-1. The lovers are numbered in sequence. The first pair is (0, 1), the second pair is (2, 3), and so on. The last pair is (2N- 2, 2N-1).
The initial seat row[i] of these couples is determined by the person who initially sat in the i-th seat.

Example:
Insert picture description here
Answer:

class Solution:
    def minSwapsCouples(self, row: List[int]) -> int:
        """
        每两个座位成一对,假定左边的人都是合法的不变,如果TA右边的人与TA匹配则
        跳过,不匹配则找到TA的匹配对象的与TA右边的人交换。
        """
        def find_another(n):
            if n % 2 == 0:
                return n + 1
            else:
                return n - 1

        c = 0
        for i in range(0, len(row), 2):
            p1 = row[i]
            p2 = find_another(p1)
            if row[i+1] != p2:
                j = row.index(p2)
                row[i+1], row[j] = row[j], row[i+1]
                c += 1

        return c

Sword refers to offer59-II

Title description:
Please define a queue and implement the function max_value to get the maximum value in the queue. The amortized time complexity of functions max_value, push_back and pop_front are all O(1).
If the queue is empty, pop_front and max_value need to return -1

Example:
Insert picture description here
Answer:

class MaxQueue:

    def __init__(self):
        self.queue = []
        self.maxq = []


    def max_value(self) -> int:
        if not self.maxq:
            return -1
        return self.maxq[0]


    def push_back(self, value: int) -> None:
        self.queue.append(value)

        while self.maxq and self.maxq[-1] < value:
            self.maxq.pop()
        self.maxq.append(value)


    def pop_front(self) -> int:
        if not self.queue:
            return -1
        v = self.queue.pop(0)
        if v == self.maxq[0]:
            self.maxq.pop(0)
        return v



# Your MaxQueue object will be instantiated and called as such:
# obj = MaxQueue()
# param_1 = obj.max_value()
# obj.push_back(value)
# param_3 = obj.pop_front()

Guess you like

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