双指针
考点:
1、collections.deque(maxlen=k)的使用
2、deque队尾插值append,队头取值的popleft()用法(或者result[0])
class Solution:
    def kthToLast(self, head: ListNode, k: int) -> int:
    
        from collections import deque
        result = deque(maxlen=k)
        result.append(head.val)
        while head:
            result.append(head.val)
            head = head.next
        return result.popleft()
考点:和上题一样
class Solution:
    def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
        from collections import deque
        result = deque(maxlen=k)
        while head:
            result.append(head)
            head = head.next
        
        return result[0]
class Solution:
    def findClosest(self, words: List[str], word1: str, word2: str) -> int:
        word1_index = None
        word2_index = None
        global result
        result = len(words)
        def refresh_result():
            global result
            if word1_index and word2_index and abs(word1_index - word2_index) < result:
                result = abs(word1_index- word2_index)
        for idx, word in enumerate(words):
            if word ==  word1:
                word1_index = idx
                refresh_result()
            elif word == word2:
                word2_index = idx
                refresh_result()
        return result
考点:
1、双指针,由前往后遍历,如果碰到比k小的值,和前面指针替换
2、技巧,该题有一个技巧,替换指针即替换元素的值
class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        left, right = head, head
        while right:
            if right.val < x:
                left.val, right.val = right.val, left.val
                left = left.next
            right = right.next
        return head
考点:
1、该题要脑经急转弯明白,该点水面积为左右最大值得较小者,减去当前点的值,python实现很简单
class Solution:
    def trap(self, height: List[int]) -> int:
        new_height = [0] + height +[0]
        result = 0
        for i in range(1, len(new_height)-1):
            left_max = max(new_height[:i])
            right_max = max(new_height[i+1:])
            if new_height[i] < left_max and new_height[i] < right_max:
                result += min(left_max, right_max) - new_height[i]
        return result
                    
                
                
            
        
浙公网安备 33010602011771号