力扣练习(一):485,283,27 对数组的简单操作

题目:给定一个二进制数组 nums , 计算其中最大连续 1 的个数

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        maxcount=count=0
        for i in nums:
            if i == 1:
                count+=1
            else:
                maxcount=max(maxcount,count)
                count=0
        maxcount=max(maxcount,count)
        return maxcount
int findMaxConsecutiveOnes(int* nums, int numsSize)
{
    int i=0,count=0,maxcount=0;
    for(i=0;i<numsSize;i++)
    {
        if(nums[i]==1)
        {
            count++;
        }
        else 
        {
            if(maxcount<=count)
            {
                maxcount=count;
                count=0;
            }
            else
            {
                count=0;
            }
        }
    }
    if(maxcount<=count)
            {
                maxcount=count;
            }
    return maxcount;
}

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作

    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        index=i=0
        n=len(nums)
        while i < n:
            if nums[i]!= 0:
                nums[index]=nums[i]
                index=index+1
            i+=1
        while index <n:
            nums[index]=0
            index+=1
void moveZeroes(int* nums, int numsSize)
{   
    int index=0;
    int i;
    for(i=0;i<numsSize;i++)
    {
        if(nums[i]!=0)
        {
            nums[index]=nums[i];
            index=index+1;
        }
    }
    for(i=index;i<numsSize;i++)
    {
        nums[i]=0;
    }

}

给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。

不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

int removeElement(int* nums, int numsSize, int val){
 int index=0,i=0;
    for(i=0;i<numsSize;i++)
    {
        if(nums[i]!=val)
        {
        nums[index]=nums[i];
        index=index+1;
        }
    }
    return index;
}
class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        index=i=0
        n=len(nums)
        while i<n:
            if nums[i]!=val:
                nums[index]=nums[i]
                index+=1
            i=i+1
        return index 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

靳小锅er

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值