当前位置:网站首页>【LeetCode】283-移动零
【LeetCode】283-移动零
2022-07-02 12:09:00 【酥酥~】
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例 2:
输入: nums = [0]
输出: [0]
提示:
- 1 <= nums.length <= 104
- -231 <= nums[i] <= 231 - 1
#笨方法
class Solution(object):
def moveZeroes(self, nums):
n = len(nums)
for i in range(n):
if nums[n-i-1]==0:
tmp = nums.pop(n-i-1)
nums.append(tmp)
#双指针,快慢指针,快指针快速遍历数列值,遇到非零数覆盖慢指针位置
class Solution(object):
def moveZeroes(self, nums):
length = len(nums)
slow = 0
for fast in range(length):
if nums[fast]:
nums[slow] = nums[fast]
slow+=1
nums[slow:]=(length-slow)*[0]
边栏推荐
猜你喜欢

Redux——详解

Bing. Com website

Data analysis thinking analysis methods and business knowledge - business indicators

19_Redis_宕机后手动配置主机

21_ Redis_ Analysis of redis cache penetration and avalanche

07_ Hash

There are 7 seats with great variety, Wuling Jiachen has outstanding product power, large humanized space, and the key price is really fragrant

06_栈和队列转换

Mavn builds nexus private server

17_ Redis_ Redis publish subscription
随机推荐
Markdown tutorial
让您的HMI更具优势,FET-G2LD-C核心板是个好选择
Storage read-write speed and network measurement based on rz/g2l | ok-g2ld-c development board
高考分数线爬取
百变大7座,五菱佳辰产品力出众,人性化大空间,关键价格真香
03_线性表_链表
Common English abbreviations for data analysis (I)
Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium
MD5加密
06_ Stack and queue conversion
Tidb cross data center deployment topology
Custom exception
Case introduction and problem analysis of microservice
2022 college students in Liaoning Province mathematical modeling a, B, C questions (related papers and model program code online disk download)
Pytoch saves tensor to Mat file
yolo格式数据集处理(xml转txt)
The traversal methods of binary tree mainly include: first order traversal, middle order traversal, second order traversal, and hierarchical traversal. First order, middle order, and second order actu
FPGA - 7系列 FPGA内部结构之Clocking -03- 时钟管理模块(CMT)
Kibana basic operation
LeetCode刷题——两整数之和#371#Medium