leetcode-4.24[35. 搜索插入位置、28. 實現 strStr()、27. 移除元素](python解法)

題目1

在這裏插入圖片描述

題解1

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        for index, num in enumerate(nums):
            if target <= num:
                return index
        return len(nums)
        

題目2

在這裏插入圖片描述

題解2

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        # 將needle作爲一個整體,只需遍歷 len(haystack) - len(needle)次
        for i in range(0, len(haystack) - len(needle) + 1):
            # 將needle的長度作爲的切片長度
 	        if haystack[i:i+len(needle)] == needle:
 	            return i
     	return -1

題目3:

在這裏插入圖片描述

題解3

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        s = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[s] = nums[i]
                s += 1
        return s
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章