代码随想录day61|215. 数组中的第K个最大元素72. 编辑距离

215. 数组中的第K个最大元素 sort()函数底层就是快排,优化比自己写要好

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        #用快排,首先找到基准数,将所有小的放到左边,大的移到右边
        #递归左数组,同时递归右数组
        #长度为1时停止递归
        # big,equal,small = [] ,[] , []
        # base = nums[0]
        # for num in nums:
        #     if num>base:
        #         big.append(num)
        #     elif num == base:
        #         equal.append(num)
        #     else:
        #         small.append(num)
        # if k<=len(big):
        #     return self.findKthLargest(big,k)
        # if len(nums)-len(small) 

72. 编辑距离

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        #动规五部曲 dp[i][j]代表word1第i-1位置之前和。。。的最少操作数
        #递推公式,if word1[i-1]==word2[j-1]分情况(增删改)
        #初始化
        # dp = [[0] *(len(word2)+1) for _ in range(len(word1)+1)]
        # for i in range(len(word1)+1):
        #     dp[i][0] = i
        # for j in range(len(word2)+1):
        #     dp[0][j] = j 
        # for i in range(1,len(word1)+1):
        #     for j in range(1,len(word2)+1):
        #         if word1[i-1] ==word2[j-1]:
        #             dp[i][j] = dp[i-1][j-1]
        #         else:
        #             #用增删改三个操作,对word1删相当于对word2增,所以增删操作保留一个就可以
        #             dp[i][j]=min(dp[i][j-1]+1,dp[i-1][j]+1,dp[i-1][j-1]+1)
        # return dp[len(word1)][len(word2)] 
        dp = [[0]*(len(word2)+1) for _ in range(len(word1)+1)]
        for i in range(len(word1)+1):
            dp[i][0]=i
        for i in range(len(word2)+1):
            dp[0][i]=i
        for i in range(1,len(word1)+1):
            for j in range(1,len(word2)+1):
                if word1[i-1]==word2[j-1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1)
        return dp[len(word1)][len(word2)]

你可能感兴趣的:(算法,leetcode,java)