LeetCode | 算法:第一个未出现的整数、编辑距离

2019-01-06  本文已影响29人  松鼠的读书笔记

41. First Missing Positive

Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
笔记:
空间换时间,时间复杂度O(n),空间复杂度O(n)

class Solution:
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 空间换时间,设置辅助数组record,记录1-n整数出现的次数
        # record[i]表示整数i+1出现的情况
        n = len(nums)
        record = [0] * n
        
        for num in nums:
            if 0 < num <= n:
                record[num-1] = 1
        
        for i in range(n):
            if record[i] == 0:
                return i+1
            
        return n + 1

72. Edit Distance

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
笔记:
动态规划。

image.png
class Solution:
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        # 动态规划
        n = len(word1)
        m = len(word2)
        
        matrix = [[i+j for j in range(m+1)] for i in range(n+1)]
        
        for i in range(1, n+1):
            for j in range(1, m+1):
                if word1[i-1] == word2[j-1]:
                    d = 0
                else:
                    d = 1
                matrix[i][j] = min(matrix[i-1][j]+1,matrix[i][j-1]+1,matrix[i-1][j-1]+d)
 
        return matrix[n][m]
上一篇下一篇

猜你喜欢

热点阅读