2021-08-16

Code 1

Question

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Answer

动态规划

class Solution(object):
    def maxProfit(self, prices):
        if len(prices)==1 or len(prices)==0 :
            return 0
        max_p=max(prices[1]-prices[0],0)
        min=prices[0]
        for i in range(0,len(prices)) :
            if prices[i]<min :
                min=prices[i]
            max_p=max(max_p,prices[i]-min)
        return max_p

动态规划 前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}

Code 2

Question

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]

Example 2

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]

Answer

  • 自己的
class Solution(object):
    def matrixReshape(self, mat, r, c):
        tot = []
        for x in mat :
            for xx in x :
                tot.append(xx)
        if len(tot)!=r*c :
            return mat

        ans=[]
        for i in range(0,r) :
            row=[]
            for j in range(0,c) :
                row.append(tot[i*c+j])
            ans.append(row)

        return ans

自己的思路 :先变成一个长条然后利用循环一个一个放入

  • 官方题解
class Solution(object):
    def matrixReshape(self, mat, r, c):

        m,n=len(mat),len(mat[0])
        if m*n!=r*c :
            return mat

        ans=[[0]*c for _ in range(r)] #初始化数组 注意这里
        for x in  range(m*n) :
            ans[x//c][x%c]=mat[x//n][x%n]

        return ans
  1. 将二维数组 nums \textit{nums} nums 映射成一个一维数组;
  2. 将这个一维数组映射回 r r r c c c 列的二维数组。
  3. 可以直接从二维数组 nums \textit{nums} nums得到 r r r c c c 列的重塑矩阵:
    (这样就比自己的解法简单)
  4. 符合前提条件的矩阵,对于 x ∈ [ 0 , m n ) x \in [0, mn) x[0,mn)第 xx 个元素在 nums \textit{nums} nums 中对应的下标为 ( x   /   n , x   %   n ) (x ~/~ n, x~\%~ n) (x / n,x % n),而在新的重塑矩阵中对应的下标为 ( x   /   c , x   %   c ) (x ~/~ c, x~\%~ c) (x / c,x % c)。我们直接进行赋值即可。(注意这一步)

Code 3

Question

Given an integer numRows, return the first numRows of Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
Example 1

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2

Input: numRows = 1
Output: [[1]]

Answer

  • 自己的解法
class Solution(object):
    def generate(self, numRows):
        if numRows==1 :
            return [[1]]
        if numRows==2 :
            return [[1],[1,1]]
        ini=[[1]]
        for i in range(1,numRows) :
            row=[1]
            for j in range (1,i) :
                row.append(ini[i-1][j-1]+ini[i-1][j])
            row.append(1)
            ini.append(row)
        return ini

属于比较常规的思路

  • 标准答案(思路相同,语法简单)
class Solution:
   def generate(self, numRows: int) -> List[List[int]]:
       ret = list()
       for i in range(numRows):
           row = list()
           for j in range(0, i + 1):
               if j == 0 or j == i:
                   row.append(1)
               else:
                   row.append(ret[i - 1][j] + ret[i - 1][j - 1])
           ret.append(row)
       return ret

这里直接把前后的1考虑在了循环里,不用像我一样分很多情况

Code 4

Question

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  • Each row must contain the digits 1-9 without repetition.
  • Each column must contain the digits 1-9 without repetition.
  • Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.

Example 1

Input: board = 
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]

Output: true

Example 2

Input: board = 
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]

Output: false

Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Answer

class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        rows=[{
    
    } for i in range(9)]
        columns=[{
    
    } for i in range(9)]
        boxes=[{
    
    } for i in range(9)]

        for i in range(9) :
            for j in range(9) :
                num=board[i][j]
                if num=='.' :
                    continue
                else :
                    num=int(num)
                    box_index=(i//3*3)+j//3

                    rows[i][num]=rows[i].get(num,0)+1
                    columns[j][num]=columns[j].get(num,0)+1
                    boxes[box_index][num]=boxes[box_index].get(num,0)+1
                    ''' 
                    rows[i].get(num, 0)
                    若不存在num,则字典rows[i]中生成num元素,并使其对应的数字为0,即rows[i] = {num:0}
                    当字典中有num元素时,作用是返回该元素对应的值
                    '''
                if rows[i].get(num,0)>1 or columns[j].get(num,0)>1 or boxes[box_index].get(num,0) >1 :
                    return False
        return True
  • 流程
  1. 首先遍历数独。
  2. 检查看到每个单元格值是否已经在当前的行 / 列 / 子独中出现过:
    • 如果出现重复,返回 false。
    • 如果没有,则保留此值以进行进一步跟踪。
  3. 返回 true。
  • 关注点
  1. 字典的初始化方式
 rows=[{
    
    } for i in range(9)]
 columns=[{
    
    } for i in range(9)]
 boxes=[{
    
    } for i in range(9)]
  1. get()的用法
    rows[i].get(num, 0)
    若不存在num,则字典rows[i]中生成num元素,并使其对应的数字为0,即rows[i] = {num:0}
    当字典中有num元素时,作用是返回该元素对应的值

Code 5

Question

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0’s, and return the matrix.
You must do it in place.
Example 1

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

Answer

  • 自己的解法
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        ismod=[]
        for x in matrix :
            row=[]
            for xx in x :
                row.append(False)
            ismod.append(row)

        for i in range(0,len(matrix)) :
            for j in range(0,len(matrix[i])) :
                if matrix[i][j]==0 and not ismod[i][j] :

                    for ii in range(0,len(matrix)) :
                        if matrix[ii][j] !=0 :
                            ismod[ii][j] = True
                        matrix[ii][j]=0


                    for jj in range(0,len(matrix[i])) :
                        if matrix[i][jj] !=0 :
                            ismod[i][jj] = True
                        matrix[i][jj]=0

                ismod[i][j]=True

        return matrix

使用了另一个list储存每一个元素的状态,然后常规思路遍历然后标记。

  • 使用标记数组
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        row,col=[False]*len(matrix),[False]*len(matrix[0])

        for i in range(len(matrix)) :
            for j in range(len(matrix[0])) :
                if matrix[i][j]==0 :
                    row[i]=col[j]=True

        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if row[i] or col[j] :
                    matrix[i][j]=0

我们首先遍历该数组一次,如果某个元素为 0 0 0,那么就将该元素所在的行和列所对应标记数组的位置置为 True \text{True} True。最后我们再次遍历该数组,用标记数组更新原数组即可。

  • 使用两个标记变量
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        m,n=len(matrix),len(matrix[0])
        flag_col0 = any(matrix[i][0] == 0 for i in range(len(matrix)))
        flag_row0 = any(matrix[0][j] == 0 for j in range(len(matrix[0])))

        for i in range(1,m) :
            for j in range(1,n) :
                if matrix[i][j]==0 :
                    matrix[0][j]=0
                    matrix[i][0]=0

        for i in range(1,m) :
            for j in range(1,n) :
                if matrix[i][0]==0 or matrix[0][j]==0 :
                    matrix[i][j]=0

        if flag_row0 :
            for j in range(n):
                matrix[0][j] = 0

        if flag_col0 :
            for j in range(m):
                matrix[j][0] = 0
        return matrix

我们可以用矩阵的第一行和第一列代替方法一中的两个标记数组。但这样会导致原数组的第一行和第一列被修改,无法记录它们是否原本包含 0。因此我们需要额外使用两个标记变量分别记录第一行和第一列是否原本包含 0。
在实际代码中,我们首先预处理出两个标记变量,接着使用其他行与列去处理第一行与第一列,然后反过来使用第一行与第一列去更新其他行与列,最后使用两个标记变量更新第一行与第一列即可。

猜你喜欢

转载自blog.csdn.net/yxyxxxyyyy/article/details/119733578