(LeetCode)雙指針

1. 移動零

283. move-zeroes
在這裏插入圖片描述

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.

        聰明解法
            1. 兩個指針,i指針迭代,j指針表示(從左往右)非零元素個數的索引,i遇到非零就複製給j
            即:把非0元素都往數組前面扔,數組後面都應該是0
            https://leetcode-cn.com/problems/move-zeroes/solution/dong-hua-yan-shi-283yi-dong-ling-by-wang_ni_ma/
            2. i不是扔,是交換
        """
        # j = 0
        # for i in xrange(len(nums)):
        #     if nums[i] != 0:
        #         nums[j] = nums[i]
        #         j += 1
        # for k in xrange(j, len(nums)):
        #     nums[k] = 0

        j = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1
                

2. 環形鏈表

141. linked-list-cycle
在這裏插入圖片描述
在這裏插入圖片描述

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool

        笨辦法
            有環說明一個節點被指向了兩次
            使用set存儲節點索引
        
        聰明法
            節點被訪問過,就把值改爲True

            雙指針,一個快指針、一個慢指針,總會相遇
        """
        if not head:
            return False
        
        slow, fast = head, head
        while slow and fast:
            slow = slow.next
            if fast.next:
                fast = fast.next.next
            else:
                return False
            if slow == fast:
                return True
        return False

3. 迴文鏈表

234. palindrome-linked-list
在這裏插入圖片描述

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool

        笨辦法
            鏈表輸出到數組,然後兩個指針前後移動檢測數組元素是否相等
            時間O(2N),空間O(N)
        """
        if not head:
            False
        
        array = []
        node = head
        while node:
            array.append(node.val)
            node = node.next
        
        i, j = 0, len(array) - 1
        while i <= j:
            if array[i] != array[j]:
                return False
            i += 1
            j -= 1
        
        return True

4. 尋找重複數

287. find-the-duplicate-number
在這裏插入圖片描述

class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int

        笨辦法
            暴力搜索
            哈希表, 統計元素出現次數, 大於1就返回
        
        聰明辦法
            快慢指針法
            可以將數組表示成一個帶環的圖: https://pic.leetcode-cn.com/f9104ccbbd4e572a8a9d6b2e7e2f75084b91c045b48e1dfc65cee238460257a1-image.png
            快慢指針都從起始位置出發, 慢指針一次走1步, 快指針一次走2步, 直到相遇
            然後, 慢指針回到起始位置, 快指針在相遇位置, 兩者同時一次走1步, 再次相遇的點即我們要的數
        """
        slow, fast = 0, 0
        while slow == fast == 0 or slow != fast:
            slow, fast = nums[slow], nums[nums[fast]]
        
        slow = 0
        while slow != fast:
            slow, fast = nums[slow], nums[fast]
        
        return slow

5. 盛最多水的容器

11. container-with-most-water
在這裏插入圖片描述
在這裏插入圖片描述

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int

        笨辦法
            暴力搜索
        
        聰明辦法
            雙指針法
            左右指針分別表示容器的左右邊界, 初始值分別爲樣本的左右邊界
            當左指針小於右指針時, 左指針右移; 否則, 右指針左移
            每次移動時, 計算當前面積, 直到左右指針相遇, 即可得最大面積
            https://leetcode-cn.com/problems/container-with-most-water/solution/sheng-zui-duo-shui-de-rong-qi-by-leetcode-solution/
        """
        max_area = 0
        left, right = 0, len(height) - 1

        while left < right:
            area = (right - left) * min(height[left], height[right])
            max_area = max(max_area, area)
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        
        return max_area

6. 相交鏈表

160. intersection-of-two-linked-lists
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode

        笨辦法
            固定A的某個節點,遍歷B的所有節點,相等返回;
            遍歷A的所有節點執行上面操作;
        
        聰明辦法
            A、B同時開始往後走;
            A走完了走B;B走完了走A;
            若相遇則返回,否則不相交;
        """
        pA, pB = headA, headB
        is_pa_linked, is_pb_linked = False, False
        while pA and pB:
            if pA == pB:
                return pA
            pA, pB= pA.next, pB.next
            if not pA and not is_pa_linked:
                pA = headB
                is_pa_linked = True
            if not pB and not is_pb_linked:
                pB = headA
                is_pb_linked = True
        return None
        

7. 迴文鏈表

234. palindrome-linked-list
在這裏插入圖片描述

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool

        思路
            鏈表輸出到數組,然後兩個指針前後移動檢測數組元素是否相等
            時間O(2N),空間O(N)
        """
        if not head:
            False
        
        array = []
        node = head
        while node:
            array.append(node.val)
            node = node.next
        
        i, j = 0, len(array) - 1
        while i <= j:
            if array[i] != array[j]:
                return False
            i += 1
            j -= 1
        
        return True

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章