1.判断链表是否存在环
https://leetcode-cn.com/problems/linked-list-cycle/
解题思路:这一题在思路上有点类似之前的寻找链表公共节点的做法,环问题可以理解为小学数学的追及问题,如果跑道是环形的,那么两个运动员一快一慢,跑的快的总会在某一个点追上跑的慢的,同样走的快的指针在存在环的链表上总会有追上走的慢的指针的时候,如果两个指针能相遇那么链表必定存在环。
class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast, slow = head, head
while slow and fast:
slow = slow.next
if fast.next:
fast = fast.next.next
else:
return False
if fast == slow:
return True
return False
2.移动零
https://leetcode-cn.com/problems/move-zeroes/submissions/
解题思路:fast指针先行探路,当检测到不为零的数,就和slow指针交换数据,同时slow指针向前移动一步
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0:
nums[slow], nums[fast] = nums[fast], nums[slow]
slow += 1
3.移除元素
https://leetcode-cn.com/problems/remove-element/
解题思路:和移动0的问题类似,将目标数字全部移动到末尾即可
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if not nums: return 0
slower, faster = 0, 0
while faster < len(nums):
if nums[slower] != val: slower += 1
elif nums[faster] != val:
nums[slower], nums[faster] = nums[faster], nums[slower]
slower += 1
faster += 1
return slower
4.删除排序数组的重复项
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
解题思路:还是快慢指针,fast先出发搜索,如果fast的值不等于slow的话,先让slow走一步保留一个重复元素,然后交换slow和fast的值。
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums: return 0
slower, faster = 0, 0
while faster< len(nums):
#当快指针指向的元素与慢指针不同时,说明相同的元素已经遍历结束,此时将慢指针后移,将快指针的元素写入慢指针位置,保留一个元素
if nums[slower] != nums[faster]:
slower += 1
nums[slower] = nums[faster]
faster += 1
return slower + 1
5.删除排序数组的重复项(加强版)
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/
解题思路:在上一题的基础上,多加一个标志位,
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums: return 0
flag = True
slower, faster = 0, 1
while faster <len(nums):
if nums[slower] != nums[faster]:
slower += 1
nums[slower] = nums[faster]
flag = True
else:
if flag:
slower += 1
nums[slower] = nums[faster]
flag = False
faster += 1
return slower + 1