leetcode刷题日记-热题100(4)

215-数组中第k个最大元素(python)
#快速选择算法-改进快排

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        def select(left,right,k_smallest):
            if left==right: return nums[left]
            pivot_index=random.randint(left,right)
            pivot_index=partion(left,right,pivot_index)
            if pivot_index==k_smallest:
                return nums[k_smallest]
            elif pivot_index>k_smallest:
                return select(left,pivot_index-1,k_smallest)
            else:
                return select(pivot_index+1,right,k_smallest)
        def partion(left,right,pivot_index):
            pivot=nums[pivot_index]
            nums[pivot_index],nums[right]=nums[right],nums[pivot_index]
            ss_index=left
            for i in range(left,right):
                if nums[i]<pivot:
                    nums[ss_index],nums[i]=nums[i],nums[ss_index]
                    ss_index+=1
            nums[right],nums[ss_index]=nums[ss_index],nums[right]
            return ss_index
        return select(0,len(nums)-1,len(nums)-k)

221-最大正方形(python)
#动态规划

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        if not matrix:return 0
        row=len(matrix)
        col=len(matrix[0])
        dp=[[0]*(col+1) for _ in range(row+1)]
        res=0
        for i in range(1,row+1):
            for j in range(1,col+1):
                if matrix[i-1][j-1]=='1':
                    dp[i][j]=min(dp[i-1][j-1],dp[i][j-1],dp[i-1][j])+1
                    res=max(res,dp[i][j]**2)
        return res

236-二叉树的最近公共祖先(python)
#递归 分为均在右子树 均在左子树以及两边

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root:
            return None
        if root == p or root == q:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if left and right:
            return root
        return left if left else right

238-除自身外数组的乘积(python)
#左右积

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
		res=[1]
		p=q=1
		for i in range(len(nums)-1):
			p*=nums[i]
			res.append(p)
		for j in range(len(nums)-1,0,-1):
			q*=nums[j]
			res[j-1]*+q
		return res

239-滑动窗口的最大值(python)
#滑动窗口

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        if not nums:
            return [] 
        window, res = [], []
        for i, num in enumerate(nums):
            # 窗口滑动时的规律
            if i>=k and window[0] <= i-k:
                window.pop(0)
            # 把最大值左边的数小的清除
            while window and nums[window[-1]] <= num:
                window.pop()
            window.append(i)
            if i >= k-1:
                res.append(nums[window[0]])
        return res

240-搜索二维矩阵(python)

class Solution:
    def searchMatrix(self,matrix,target):
    	row=len(matrix)
    	col=len(matrix[0])
    	i,j=0,col-1
    	while i<row and j >=0:
    		if matrix[i][j]>target:
    			j-=1
    		elif matrix[i][j]<target:
    			i+=1
    		else:
    			return True
    	return False

279-完全平方数(python)
#四平方定理

class Solution:
    def numSquares(self, n: int) -> int:
        import math
        while n % 4 == 0: n = n // 4
        if n % 8 == 7: return 4
        if int(math.sqrt(n)) ** 2 == n: return 1
        i = 1
        while i*i <= n:
            j = math.sqrt(n - i*i)
            if int(j) == j: return 2
            i += 1
        return 3 

283-移动0至末尾(python)
#双指针

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
    	j=0
		for i in range(len(nums)):
			if nums[i]!=0:
				nums[i],nums[j]=nums[i],nums[j]
				j+=1
		return nums

287-寻找重复数(python)
#排序后比较

class Solution:
    def findDuplicate(self,nums):
    	nums.sort()
    	for i in range(1,len(nums)):
    		if nums[i]==nums[i-1]:
    			return nums[i]

297-二叉树的序列化与反序列化(python)

class Codec:
    def serialize(self, root):
        def rserialize(root, string):
            if root is None:
                string += 'None,'
            else:
                string += str(root.val) + ','
                string = rserialize(root.left, string)
                string = rserialize(root.right, string)
            return string        
        return rserialize(root, '')
    def deserialize(self, data):
        def rdeserialize(l):
            if l[0] == 'None':
                l.pop(0)
                return None                
            root = TreeNode(l[0])
            l.pop(0)
            root.left = rdeserialize(l)
            root.right = rdeserialize(l)
            return root
        data_list = data.split(',')
        root = rdeserialize(data_list)
        return root

300-最长上升子序列(python)

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        if not nums:
            return 0
        dp=[1]*len(nums)
        for i in range(len(nums)):
            for j in range(i):
                if nums[j]<nums[i]:
                    dp[i]=max(dp[i],dp[j]+1)
        return max(dp) 

322-零钱兑换(python)

class Solution(object):
    def coinChange(self, coins, amount):
	    dp = [amount + 1 for _ in range(amount + 1)]
	    dp[0] = 0
	    # 到amount总金额(金额当索引)
	    for i in range(1, amount + 1):
	        for j in range(len(coins)):
	            # 只有硬币小于当前金额, 才能进行递推
	            if coins[j] <= i:
	                # dp[i]要么等于自身(已经被计算过),
	                # 要么等于coins[j](一次) + (i - coins[j])的次数
	                dp[i] = min(dp[i], dp[i-coins[j]] + 1)
	    return -1 if dp[amount] > amount else dp[amount]

你可能感兴趣的:(leetcode刷题日记-热题100(4))