zoukankan      html  css  js  c++  java
  • leetcode_283_移动零

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
    
    示例:
    
    输入: [0,1,0,3,12]
    输出: [1,3,12,0,0]
    说明:
    
    必须在原数组上操作,不能拷贝额外的数组。
    尽量减少操作次数。
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/move-zeroes
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    #方法1:快慢双指针
    class Solution:
        def moveZeroes(self, nums: List[int]) -> None:
            """
            Do not return anything, modify nums in-place instead.
            """
            p1=p2=0
            length_of_nums=len(nums)
            #如果p2指向的值是0,p2++,否则与p1指向的值交换,p1左边是已经处理好的数
            while(p2<length_of_nums):
                if nums[p2]!=0 :
                    nums[p1],nums[p2]=nums[p2],nums[p1]
                    p1+=1
                p2+=1
    
    #方法2:单指针,先把不是0个向前移到指针的位置
    class Solution:
        def moveZeroes(self, nums: List[int]) -> None:
            """
            Do not return anything, modify nums in-place instead.
            """
            p1=0
            length=len(nums)
            for x in nums:
                if x!=0:
                    nums[p1]=x
                    p1+=1
            for t in range(p1,length):
                nums[t]=0
    
  • 相关阅读:
    AC3 encoder flow
    AC3 IMDCT
    AC3 Rematrix
    AC3 channel coupling
    AC3 mantissa quantization and decoding
    AC3 bit allocation
    AC3 exponent coding
    C# 判断字符串为数字 int float double
    vs 修改默认的调试浏览器
    visio 如何扩大画布大小
  • 原文地址:https://www.cnblogs.com/hqzxwm/p/14005020.html
Copyright © 2011-2022 走看看