2024-09-09 Leetcode刷题

2024-09-10 08:27:29 浏览数 (3)

First Question

快慢指针

代码语言:javascript复制
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        slow,fast = 0,1
        while fast < len(nums):
            if nums[fast] == nums[slow]:
                fast =1;
            else:
                nums[slow 1] = nums[fast]
                fast  = 1
                slow  = 1
        return slow 1

Second Question

利用指针进行计数,后通过所计的数可以很方便的找到要替换的准确的位置

代码语言:javascript复制
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        offset = 0
        for i in range(len(nums)):
            if nums[i] == 0:
                offset  = 1
            elif nums[i] != 0 and offset > 0:
                nums[i-offset] = nums[i]
                nums[i] = 0

Third Question

要记录的是连续1,所以要在计数该断的时候断(即遇到不是1的时候)

代码语言:javascript复制
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        max,count = 0,0
        for i in range(len(nums)):
            if nums[i] == 1:
                count  = 1
            else:
                count = 0
            if count > max:
                max = count
        return max

Fourth Question

题目只要求前K歌元素包含不等于val的元素,所以只需要把不是val的元素全部放在数组前面,并记录元素个数即可

代码语言:javascript复制
class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0;
        for x in nums:
            if x != val:
                nums[i] = x
                i =1
        return i

0 人点赞