行业知识
力扣题库第4题:移动零
2026-11-09 18:32:26
来源:互联网转载
题目内容:
���定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
()请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 :
输入: nums = [0,1,0,3,12]
()输出: [1,3,12,0,0]
答案:
# coding:utf-8# 时间:2024/3/7 21:42# Pythonit教程网(blog.pythonit.cn)# Python全栈视频课件获取:www.dqu.cc# 加速高防cdn:woaiyundun.cndef move_zeroes(nums): # 初始化一个指针指向非零元素的下一个位置 write_index = 0 # 遍历数组 for read_index in range(len(nums)): # 如果当前元素不是0 if nums[read_index] != 0: # 将当前元素放到write_index的位置 nums[write_index] = nums[read_index] # 将write_index向前移动一位 write_index += 1 # 遍历结束后,write_index之后的位置都应该是0 # 因为我们只需要保证非零元素在write_index之前,所以直接在后面填充0即可 for i in range(write_index, len(nums)): nums[i] = 0nums = [0, 1, 0, 3, 12]move_zeroes(nums)print(nums) # 输出应该是 [1, 3, 12, 0, 0]
上一篇:MySQL中空值和NULL的区别,开发过程中注意必坑!
下一篇:服务器怎么写代码?