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

139-单词划分(python)
#动态规划

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        dp = [False] * (len(s) + 1)        
        dp[0] = True        
        for i in range(1,len(s) + 1):   # 第一层循环是字符串            
            for word in wordDict:   # 循环每个dict,看是否能装进去                
                if (i >= len(word) and s[i - len(word):i] == word):  # 这里注意,需要满足当前str[i-len(word):i]  的字符串正好等于dict中的字符串。
                    dp[i] = dp[i] or dp[i-len(word)]   # 取一个能装进去的就是True        
        return dp[-1]

141-环形链表,判断是否有环(python)
#快慢指针

class Solution:
	def hasCycle(self,head):
		fast,slow=head,head
		while fast and fast.next:
			fast=fast.next.next
			slow=slow.next
			if fast==slow:return True
		return False

142-环形链表2,找环的入口节点(python)
#快慢指针后

class Solution:
	def detectCycle(self,head):
		fast,slow=head,head
		while True:
			fast=fast.next.next
			slow=slow.next
			if fast==slow:break
		fast=head
		while fast!=slow:
			fast=fast.next
			slow=slow.next
		return fast

146-LRU缓存机制(python)

class Node:
    def __init__(self, key, val):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None
class LRUCache:

    def __init__(self, capacity: int):
        # 构建首尾节点, 使之相连
        self.head = Node(0, 0)
        self.tail = Node(0, 0)
        self.head.next = self.tail
        self.tail.prev = self.head

        self.lookup = dict()
        self.max_len = capacity

    def get(self, key: int) -> int:
        if key in self.lookup:
            node = self.lookup[key]
            self.remove(node)
            self.add(node)
            return node.val
        else:
            return -1

    def put(self, key: int, value: int) -> None:
        if key in self.lookup:
            self.remove(self.lookup[key])
        if len(self.lookup) == self.max_len:
            # 把表头位置节点删除(说明最近的数据值)
            self.remove(self.head.next)
        self.add(Node(key, value))
    # 删除链表节点
    def remove(self, node):
        del self.lookup[node.key]
        node.prev.next = node.next
        node.next.prev = node.prev
    # 加在链表尾
    def add(self, node):
        self.lookup[node.key] = node
        pre_tail = self.tail.prev
        node.next = self.tail
        self.tail.prev = node
        pre_tail.next = node
        node.prev = pre_tail

148-排序链表(python)
#归并排序

class Solution:
	def sortlist(self,head):
		if not head or not head.next:return head
		fast,slow=head,head
		while fast and fast.next:
			fast=fast.next.next
			slow=slow.next
		mid=slow.next
		slow.next=None
		left=self.sortlist(head)
		right=self.sortlist(mid)
		h=res=ListNode(0)
		whiel left and right:
			if left.val<right.val:
				h.next=left
				left=left.next
			else:
				h.next=right
				right=right.next
			h=h.next
		h.next=left if left else right
		return res.next

152-乘积最大子数组(python)
#负数交换最大值最小值

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        mi=ma=res=nums[0]
        for i in range(1,len(nums)):
            if nums[i]<0:mi,ma=ma,mi
            ma=max(ma*nums[i],nums[i])
            mi=min(mi*nums[i],nums[i])
            res=max(ma,res)
        return res

160-相交链表(python)
#a+b+c c+b+a相遇的点是交点或者为None

class Solution:
	def GetIntersectionNode(self,headA,headB):
		ha,hb=headA,headB
		while ha!=hb:
			ha=ha.next if ha else hb
			hb=hb.next if hb else ha
		return ha

169-多数元素(python)

class Solution:
	def majorityElement(self,nums):
		nums.sort()
		return nums[len(nums)//2]

198-打家劫舍(python)
#动态规划-

class Solution:
    def rob(self, nums: List[int]) -> int:
	    if len(nums) == 0:
	        return 0
	    dp = [0] * (len(nums)+1)
	    dp[0] = 0
	    dp[1] = nums[0]
	    for k in range(2, len(nums)+1):
	        dp[k] = max(dp[k-1], nums[k-1] + dp[k-2])
	    return dp[-1]

200-岛屿数量(python)
#深度优先

class Solution(object):
    directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    def numIslands(self, grid):
        m = len(grid)
        # 特判
        if m == 0:
            return 0
        n = len(grid[0])
        marked = [[False for _ in range(n)] for _ in range(m)]
        count = 0
        # 从第 1 行、第 1 格开始,对每一格尝试进行一次 DFS 操作
        for i in range(m):
            for j in range(n):
                # 只要是陆地,且没有被访问过的,就可以使用 DFS 发现与之相连的陆地,并进行标记
                if not marked[i][j] and grid[i][j] == '1':
                    count += 1
                    self.__dfs(grid, i, j, m, n, marked)
        return count
    def __dfs(self, grid, i, j, m, n, marked):
        marked[i][j] = True
        for direction in self.directions:
            new_i = i + direction[0]
            new_j = j + direction[1]
            if 0 <= new_i < m and 0 <= new_j < n and not marked[new_i][new_j] and grid[new_i][new_j] == '1':
                self.__dfs(grid, new_i, new_j, m, n, marked)

206-反转链表(python)

class Solution:
	def reverseList(self,head):
		pre=None
		cur=head
		while cur:
			temp=cur.next
			cur.next=pre
			pre=cur
			cur=temp
		return cur

226-反转二叉树(python)
#交换后递归

class Solution:
	def invertTree(self,root)if not root:return 
		if root.left==None and root.right=None:return root
		temp=root.left
		root.left=root.right
		root.right=temp
		self.invertTree(root.left)
		self.invertTree(root.right)
		return root

739-每日温度(python)

class Solution(object):
    def dailyTemperatures(self, T):
        stack=[]
        ans=[0]*len(T)
        for i in range(len(T)-1,-1,-1):
            while stack and T[i]>=T[stack[-1]]:
                stack.pop()
            if stack:
                ans[i]=stack[-1]-i
            stack.append(i)
        return ans

234-回文链表(python)
#快慢指针找中点,后半部分反转链表,比较。

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if not head or not head.next:return True
        # 取中位数的上边界,比如[1, 2, 2, 3] 取到是第二个2
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        # 奇数时候,中点位置下一个,(这样翻转才一样)
        if fast:
            slow = slow.next
        # 翻转操作
        prev = None
        cur = slow
        while cur:
            tmp = cur.next
            cur.next = prev
            prev = cur
            cur = tmp
        # 对比
        p1 = head
        p2 = prev
        while p1 and p2:
            if p1.val != p2.val:
                return False
            p1 = p1.next
            p2 = p2.next
        return True

217-存在重复元素(python)
#排序后比较

class Solution(object):
    def containsDuplicate(self, nums):
        if not nums:
            return False
        nums.sort()
        for i in range(1,len(nums)):
            if nums[i]==nums[i-1]:
                return True
        return False

219-存在重复元素二(python)
#key-value

class Solution:
	def containsNearbyDuplication(self,nums,k):
		lookup={}
		if len(nums)==len(set(nums)):return False
		for idx,num in enumerate(nums):
			if nums in lookup and idx-lookup[num]<=k:
				return True
			lookup[num]=idx
		return False

617-合并二叉树(python)
#递归

class Solution:
	def mergeTrees(self,t1,t2):
		if not t1:return t2
		if not t2:return t1
		root=TreeNode(t1.val+t2.val)
		root.left=self.mergeTrees(t1.left,t2.left)
		root.right=self.mergeTrees(t1.right,t2.right)
		return root

560-和为k的子数组(python)

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        hash={0:1}
        sum=0
        count=0
        for i in range(len(nums)):
            sum+=nums[i]
            if((sum-k) in hash):
                count+=hash[sum-k]
            if(sum in hash):
                hash[sum]+=1
            else:
                hash[sum]=1
        return count

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