一个人只做网站的流程,做原创视频网站,谷歌关键词排名优化,网络运维工程师的月薪有多少本文为Python算法题集之一的代码示例
题目283#xff1a;移动零
说明#xff1a;给定一个数组 nums#xff0c;编写一个函数将所有 0 移动到数组的末尾#xff0c;同时保持非零元素的相对顺序
注意 #xff0c;必须在不复制数组的情况下原地对数组进行操作
本文给出四…本文为Python算法题集之一的代码示例
题目283移动零
说明给定一个数组 nums编写一个函数将所有 0 移动到数组的末尾同时保持非零元素的相对顺序
注意 必须在不复制数组的情况下原地对数组进行操作
本文给出四种解法结果均正确不过只有一个是合乎题意的 Python3.7以上新特性代码简洁优雅结果正确但技术过于先进此题不认可 from itertools import groupbydef move_zeros_to_end_ext3(nums):if len(nums) 2:return numsreturn [i for k, g in groupby(nums) if k ! 0 for i in g] [i for k, g in groupby(nums) if k 0 for i in g]print(move_zeros_to_end_ext3([0, 1, 0, 3, 12]))
# 运行结果
[1, 3, 12, 0, 0]使用数组复制结果正确违反限制此题不认可 def move_zeros_to_end_ext2(nums):if len(nums) 2:return numszeros []non_zeros []for num in nums:if num 0:zeros.append(num)else:non_zeros.append(num)return non_zeros zerosprint(move_zeros_to_end_ext2([0, 1, 0, 3, 12]))
# 运行结果
[1, 3, 12, 0, 0]从后往前进行块移动结果正确步骤最长超时失败 def move_zeros_to_end_timeout(nums):if len(nums) 2:return numsleft, right len(nums) - 2, len(nums) - 1while right 0:if nums[right] 0:right - 1left right -1continuewhile left 0:if nums[left] 0:for iIdx in range(right - left):nums[leftiIdx] nums[leftiIdx1]nums[right] 0right - 1left right - 1continueleft - 1right - 1left right - 1return numsprint(move_zeros_to_end_timeout([0, 1, 0, 3, 12]))
# 运行结果
[1, 3, 12, 0, 0]使用零数量计数器所有元素最多移动一次结果正确通过算法验证 def move_zeros_to_end_ext1(nums):if len(nums) 2:return numsiZeroCount 0left, right 0, len(nums) - 1while left right:if nums[left] 0:iZeroCount 1else:nums[left - iZeroCount] nums[left]left 1left - iZeroCountwhile left right:nums[left] 0left 1return numsprint(move_zeros_to_end_ext1([0, 1, 0, 3, 12]))
# 运行结果
[1, 3, 12, 0, 0]第四种解法效果还行如图
一日练一日功一日不练十日空
may the odds be ever in your favor ~