当前位置:网站首页>【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]
边栏推荐
- Tidb environment and system configuration check
- 怎样从微信返回的json字符串中截取某个key的值?
- 08_ strand
- Build your own semantic segmentation platform deeplabv3+
- Tidb hybrid deployment topology
- MySQL -- Index Optimization -- order by
- XML Configuration File
- Real estate market trend outlook in 2022
- Application of CDN in game field
- 6.12 critical moment of Unified Process Platform
猜你喜欢

Semantic segmentation learning notes (1)

终于搞懂了JS中的事件循环,同步/异步,微任务/宏任务,运行机制(附笔试题)

MySQL -- Index Optimization -- order by

02_ Linear table_ Sequence table

15_Redis_Redis.conf详解

20_ Redis_ Sentinel mode

【网络安全】网络资产收集

FPGA - clock-03-clock management module (CMT) of internal structure of 7 Series FPGA

自定义异常

Equipped with Ti am62x processor, Feiling fet6254-c core board is launched!
随机推荐
5. Practice: jctree implements the annotation processor at compile time
LeetCode刷题——递增的三元子序列#334#Medium
02. After containerization, you must face golang
07_ Hash
13_ Redis_ affair
PHP method to get the index value of the array item with the largest key value in the array
Libcurl Lesson 13 static library introduces OpenSSL compilation dependency
LeetCode刷题——奇偶链表#328#Medium
Steps for Navicat to create a new database
How to choose a third-party software testing organization for automated acceptance testing of mobile applications
MD5 encryption
Oracle primary key auto increment
04_ 栈
提前批院校名称
03_ Linear table_ Linked list
党史纪实主题公益数字文创产品正式上线
LeetCode刷题——去除重复字母#316#Medium
03. Preliminary use of golang
Topology architecture of the minimum deployment of tidb cluster
. Net again! Happy 20th birthday