zoukankan      html  css  js  c++  java
  • 【python刷题】数组链表去重

    数组去重

    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
    
  • 相关阅读:
    ASP.NET面试题(二)
    iBatis.Net系列(四) iBatisNet API基础
    ibatisnet系列(一) 总览
    iBatisnet系列(二) 配置运行环境和日志处理
    HDU 1575 Tr A (矩阵乘法)
    HDU 连连看
    1504: ZZ的橱柜 (优先队列)
    离散化思想
    POJ 2777 Count Color (线段树)
    POJ 1823 Hotel (线段树)
  • 原文地址:https://www.cnblogs.com/xiximayou/p/14371505.html
Copyright © 2011-2022 走看看