【leetcode 26 27 28】Remove Duplicates from Sorted Array & Remove Element & Implement strStr()

本文提供了三道LeetCode经典题目“删除排序数组中的重复项”、“移除元素”及“实现strStr()”的Python解决方案。通过简洁有效的代码示例,帮助读者理解这些常见算法问题的解决思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
https://leetcode.com/problems/remove-element
https://leetcode.com/problems/implement-strstr
这几个比较容易,就直接记录一下代码了。
Remove Duplicates from Sorted Array

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        i = 0
        count = 0
        while i < len(nums)-1:
            while nums[i] == nums[i+1]:
                del nums[i + 1]
                if i == len(nums)-1:
                    break
            i += 1
        return len(nums)

Remove Element

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        while val in nums:
            nums.remove(val)
        return len(nums)
        

Implement strStr()

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """

        if not needle or haystack==needle:
            return 0
        i = 0

        while i <= len(haystack) - len(needle):
            if haystack[i] == needle[0]:
                if haystack[i:i + len(needle)] == needle:
                    return i
            i += 1
        return -1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值