当前位置:网站首页>leetcode 283:移动零
leetcode 283:移动零
2022-08-10 03:16:00 【Rolandxxx】
题目描述:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
自己的第一遍解法,for循环里参杂while,O(N2)的时间复杂度,耗时太多
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
""" Do not return anything, modify nums in-place instead. """
if nums is None or len(nums)==0 or len(nums)==1:
return nums
for i, num in enumerate(nums):
if nums[i] == 0:
cur = i
if cur == len(nums)-1:
return nums
while nums[cur+1]==0:
cur += 1
if cur == len(nums)-1:
return nums
tmp = nums[i]
nums[i] = nums[cur+1]
nums[cur+1] = tmp
return nums
优化解法:直接遍历一遍数组,碰到把不为0的值直接就按顺序放到数组index以0开始的对应位置上去,以此递增。
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
""" Do not return anything, modify nums in-place instead. """
index = 0
for num in nums:
if num != 0:
nums[index] = num
index += 1
for i in range(index,len(nums)):
nums[i]=0
边栏推荐
猜你喜欢
随机推荐
Example 043: Scope, class methods and variables
flex 的 三个参数:flex-grow、flex-shrink、flex-basis
flutter 创建可增型列表和列表排序
proxy代理服务
shell文本编辑awk
flink 12 源码编译及使用idea运行、debug
It's almost 35, still "did a little"?What happened to the test workers who had been in the industry for a few years?
如何使用腾讯字体,已经在什么场合下可以使用该字体?TTTGB-Medium
黑马jvm课程笔记d2
Little rookie Hebei Unicom induction training essay
请教各位confluence部署连接数据库成功,但是在后面建表设置的时候报错
轻流CEO薄智元:从无代码到无边界
(面试加分新技能) 总结11个ES2022中你可能遗漏的语法
湖仓一体电商项目(四):项目数据种类与采集
树的介绍、树的定义和基本术语、二叉树的定义和性质、二叉树的顺序表示与实现和链式表示与实现以及树的遍历方法以及两种创建方式
维度表设计
常用类以及接口
flutter异步
How does a new tester do functional testing?Test thinking is really important
【单调栈】【概念讲解&&模板代码】