数组去重
def removeDuplicates(nums):
n = len(nums)
if n == 0:
return 0
slow,fast = 0,1
while fast < n:
if nums[fast] != nums[slow]:
slow += 1
nums[slow] = nums[fast]
fast += 1
return slow + 1
nums = [0,0,1,1,1,1,2,2,3,3,3,4]
res = removeDuplicates(nums)
print(nums[:res])
链表去重
def deleteDuplicates(head):
if not head:
return None
slow = head
fast = head.next
while fast != None:
if fast.val == slow.val:
slow.next = fast
slow = slow.next
fast = fast.next
slow.next = None
return head
leetcode 316 去除重复字母
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
from collections import Counter
stack = []
instack = {chr(i):-1 for i in range(256)}
count = Counter(s)
for c in s:
count[c] -= 1
if instack[c] == 1:
continue
while len(stack) > 0 and stack[-1] > c:
if count[stack[-1]] == 0:
break
instack[stack.pop()] = 0
stack.append(c)
instack[c] = 1
return "".join(stack)
leetcode 27 移动元素
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
slow, fast = 0,0
while fast < len(nums):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
leetcode 283 移动0
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
slow, fast = 0,0
while fast < len(nums):
if nums[fast] != 0:
nums[slow],nums[fast] = nums[fast],nums[slow]
slow += 1
fast += 1